Java Spring Security
程序员文章站
2022-06-28 17:08:11
show me your code...
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>zhibing_mybatis</display-name> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring.xml,classpath:spring-mvc.xml,classpath:spring-security.xml </param-value> </context-param> <!-- 加载其他的xml配置 --> <context-param> <param-name>logbackConfigLocation</param-name> <param-value>classpath:logback.xml</param-value> </context-param> <!-- logback监听器(注意顺序,在spring监听器上面) --> <listener> <listener-class>ch.qos.logback.classic.servlet.LogbackServletContextListener</listener-class> </listener> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> <init-param> <param-name>loginUsername</param-name> <param-value>admin</param-value> </init-param> <init-param> <param-name>loginPassword</param-name> <param-value>root123</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> <filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>LocalSecurityFilter</filter-name> <filter-class>org.aaa.security.service.LocalSecurityFilter</filter-class> </filter> <filter-mapping> <filter-name>LocalSecurityFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> </filter> <filter-mapping> <filter-name>springSecurityFilterChain</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <listener> <description>spring listener</description> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <description>spring mvc servlet</description> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextClass</param-name> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <session-config> <session-timeout>600</session-timeout> </session-config> <welcome-file-list> <welcome-file>starter.html</welcome-file> </welcome-file-list> </web-app>
spring-security.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd"> <import resource="spring-security-jdbc.xml"/> </beans>
spring-security-jdbc.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:security="http://www.springframework.org/schema/security" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd"> <security:http auto-config="true"> <security:intercept-url pattern="/lib/**" access="permitAll"/> <security:intercept-url pattern="/dist/**" access="permitAll"/> <security:intercept-url pattern="/bootstrap/**" access="permitAll"/> <security:intercept-url pattern="/plugins/**" access="permitAll"/> <security:intercept-url pattern="/js/**" access="permitAll"/> <security:intercept-url pattern="/login**" access="permitAll"/> <security:intercept-url pattern="/css/**" access="permitAll"/> <security:intercept-url pattern="/imgs/**" access="permitAll"/> <security:intercept-url pattern="/org/**" access="permitAll"/> <security:intercept-url pattern="/commons/getCurrentUser**" access="permitAll"/> <security:intercept-url pattern="/commons/getsessionerrmsg.do" access="permitAll"/> <security:intercept-url pattern="/hs" access="permitAll"/> <security:intercept-url pattern="/api/getImRuleList.do" access="permitAll"/> <security:intercept-url pattern="/**" access="!anonymous"/> <security:form-login login-page="/login.do" username-parameter="username" password-parameter="password" default-target-url="/starter.html#/config/index" always-use-default-target="true" authentication-details-source-ref="authenticationDetailsSource"/> <security:logout logout-url="/j_spring_cas_security_logout"/> <security:remember-me remember-me-parameter="remember_me"/> <security:csrf disabled="true"/> <security:custom-filter ref="myAuthentication" before="FORM_LOGIN_FILTER"/> </security:http> <security:authentication-manager alias="authenticationManager"> <security:authentication-provider ref="shareAuthenticationProviderDecorator"/> </security:authentication-manager> <bean id="myAuthentication" class="org.aaa.security.service.MyAuthenticationProcessingFilter"> <property name="authenticationManager" ref="authenticationManager"/> </bean> <bean id="shareAuthenticationProviderDecorator" class="org.aaa.security.service.ShareAuthenticationProviderDecorator"> <property name="authenticationProvider" ref="daoAuthenticationProvider"/> </bean> <bean id="authenticationDetailsSource" class="org.aaa.security.service.CustomAuthenticationDetailsSource"/> <bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider"> <property name="userDetailsService" ref="userDetailsService"/> <property name="passwordEncoder" ref="passwordEncoder"/> </bean> <bean id="userDetailsService" class="org.aaa.security.service.DbUserDetailService"> <property name="dataSource" ref="dataSource"> </property> <property name="authoritiesByUsernameQuery"> <value> <![CDATA[SELECT login_name username, 'admin' AS authority
FROM rhinoce_user
WHERE isactive = 1 and login_name = ?
]]> </value> </property> <property name="usersByUsernameQuery"> <value> <![CDATA[SELECT user_id,user_name,login_name, user_password, 1 AS enabled,user_type,user_department_type
FROM rhinoce_user
WHERE isactive = 1 and login_name = ? ]]> </value> </property> </bean> <bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.Md5PasswordEncoder"/> <bean id="dbAuthenticationService" class="org.aaa.security.service.DefaultAuthenticationService"/> </beans>
UserVo
public class UserVo { private String userId; private String company; private String department; private String name; private Integer userType; private String userDepartmentType; private String roleName; private String username; }
SessionMeta
@Data @NoArgsConstructor @AllArgsConstructor public class SessionMeta { private Long timeflag; private User user;
WebConfig
import org.springframework.context.annotation.*; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import java.nio.charset.Charset; import java.util.List; @Configuration @EnableWebMvc @ComponentScan(basePackages = {"org.aaa.controller"}) @PropertySource(value = {"classpath:config.properties"}) @EnableAspectJAutoProxy(proxyTargetClass = true) public class WebConfig extends WebMvcConfigurerAdapter { @Bean public RequestMappingHandlerAdapter requestMappingHandlerAdapter() { RequestMappingHandlerAdapter adapter = new RequestMappingHandlerAdapter(); // @ResponseBody注解靠HttpMessageConverter解析 List<HttpMessageConverter<?>> converters = adapter.getMessageConverters(); // 移除默认编码为ISO8859-1的字符串解析器 converters.removeIf(converter -> converter instanceof StringHttpMessageConverter); converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8)); // 字符串才使用UTF-8解析 converters.add(new MappingJackson2HttpMessageConverter()); // 解析json adapter.setMessageConverters(converters); return adapter; } @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigIn() { return new PropertySourcesPlaceholderConfigurer(); } }
DefaultAuthenticationService
import com.alibaba.fastjson.JSONObject; import org.aaa.base.SessionMeta; import org.aaa.constant.RhinocerosConstant; import org.aaa.dto.User; import org.aaa.dto.UserVo; import org.aaa.services.AuthenticationService; import org.aaa.util.SessionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import redis.clients.jedis.JedisCluster; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; public class DefaultAuthenticationService implements AuthenticationService, InitializingBean { private final static Logger logger = LoggerFactory.getLogger(DefaultAuthenticationService.class); static ConcurrentHashMap<String, SessionMeta> sessionCacheMap = new ConcurrentHashMap<>(); public static ConcurrentHashMap<String, Object> strCacheMap = new ConcurrentHashMap<>(); @Value("${session.url}") private String sessionUrl; @Autowired private JedisCluster jedisCluster; public String getSessionUrl() { return sessionUrl; } @Override public User getCurrentUser() { /**
* 改用session共享 start
*/ String seesionId = null; String res = null; try { seesionId = SessionUtil.getSessionId(); if (seesionId != null) { if (sessionCacheMap.get(seesionId) != null) { if ((System.currentTimeMillis() - sessionCacheMap.get(seesionId).getTimeflag()) <= 500) { //合法时间 User user = sessionCacheMap.get(seesionId).getUser(); sessionCacheMap.put(seesionId, new SessionMeta(System.currentTimeMillis(), user)); return user; } else { //没有缓存 res = SessionUtil.get(sessionUrl, seesionId); if (res != null && !"".equals(res)) { JSONObject res0 = JSONObject.parseObject(res); if (res0.getBoolean(RhinocerosConstant.status)) { UserVo uservo = JSONObject.parseObject(JSONObject.parseObject(res).getString("val"), UserVo.class); User user = new User(uservo.getUsername(), "", new ArrayList<>()); user.setUserId(uservo.getUserId()); user.setUserType(uservo.getUserType()); user.setUserDepartmentType(uservo.getUserDepartmentType()); sessionCacheMap.put(seesionId, new SessionMeta(System.currentTimeMillis(), user)); return user; } } } } else { //没有缓存 res = SessionUtil.get(sessionUrl, seesionId); if (res != null && !"".equals(res)) { JSONObject res0 = JSONObject.parseObject(res); if (res0.getBoolean(RhinocerosConstant.status)) { UserVo uservo = JSONObject.parseObject(JSONObject.parseObject(res).getString("val"), UserVo.class); User user = new User(uservo.getUsername(), "", new ArrayList<>()); user.setUserId(uservo.getUserId()); user.setUserType(uservo.getUserType()); user.setUserDepartmentType(uservo.getUserDepartmentType()); sessionCacheMap.put(seesionId, new SessionMeta(System.currentTimeMillis(), user)); return user; } } } } } catch (Exception e) { logger.error("会话异常 defaultAuthenticationService exception sessionId:{} ,res={}", seesionId, res, e); } logger.error("loss sessionId defaultAuthenticationService exception sessionId:{} ,res={}", seesionId, res); // end SecurityContext context = SecurityContextHolder.getContext(); if (context == null) { return null; } Authentication authentication = context.getAuthentication(); if (authentication == null) { return null; } try { // add by guyan2017-04-12 return (User) authentication.getPrincipal(); // add by guyan2017-04-12 start } catch (Exception e) { return null; } // add by guyan2017-04-12 end } @Override public void afterPropertiesSet() { new Thread(() -> { try { while (sessionUrl == null) { Thread.sleep(1000); } strCacheMap.put(RhinocerosConstant.sessionUrl, sessionUrl); while (jedisCluster == null) { Thread.sleep(1000); } strCacheMap.put(RhinocerosConstant.jedisCluster, jedisCluster); } catch (Exception e) { logger.error("afterPropertiesSet exception", e); } }).start(); } }
ShareAuthenticationProviderDecorator
import com.alibaba.fastjson.JSONObject; import com.google.common.base.Charsets; import com.google.common.hash.Hashing; import org.aaa.dao.UserDao; import org.aaa.pojo.RhinoceUser; import org.aaa.security.ShareAuthenticationToken; import org.aaa.util.SessionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import javax.naming.Context; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.servlet.http.HttpSession; import java.util.Hashtable; public class ShareAuthenticationProviderDecorator implements AuthenticationProvider { private static final Logger logger = LoggerFactory.getLogger(ShareAuthenticationProviderDecorator.class); @Value("${domainIp}") private String domainIp; @Value("${domianPort}") private String domianPort; @Value("${domianName}") private String domianName; @Autowired private UserDao userDao; @Value("${session.url}") private String sessionUrl; private AuthenticationProvider authenticationProvider; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { if (authentication instanceof ShareAuthenticationToken) { return authentication; } else { CustomWebAuthenticationDetails details = (CustomWebAuthenticationDetails) authentication.getDetails(); HttpSession session = details.getSession(); RhinoceUser user = userDao.getUserByLoginName(authentication.getPrincipal() + ""); if (user != null && user.getUserType() != 1) { //usertype=1 系统用户,usertype !=1 域用户 boolean flag = false; try { flag = checkDomain(domianName + "\\" + authentication.getPrincipal() + "", authentication.getCredentials() + ""); } catch (Exception e) { flag = false; } if (!flag) { logger.error("authenticate exception1 Principal:{}", authentication.getPrincipal()); session.setAttribute("errmsg", "账号或密码错误"); return null; } else { String md5 = Hashing.md5().newHasher().putString(authentication.getCredentials() + "", Charsets.UTF_8).hash().toString(); userDao.updateUserPasswordByUserId(user.getUserId(), md5); } } else { return null; } try { Authentication ac = authenticationProvider.authenticate(authentication); String sessionId = SessionUtil.getSessionId(user.getLoginName()); SessionUtil.set(sessionUrl, sessionId, JSONObject.toJSONString(user)); DefaultAuthenticationService.sessionCacheMap.remove(sessionId); session.removeAttribute("errmsg"); return ac; } catch (AuthenticationException e) { logger.error("authenticate exception2 Principal:{}", authentication.getPrincipal(), e); session.setAttribute("errmsg", "账号或密码错误"); throw e; } } } @Override public boolean supports(Class<?> aClass) { if (aClass.equals(ShareAuthenticationToken.class)) { return true; } else { return authenticationProvider.supports(aClass); } } public void setAuthenticationProvider(AuthenticationProvider authenticationProvider) { this.authenticationProvider = authenticationProvider; } private Boolean checkDomain(String userName, String password) { String url = "ldap://" + domainIp + ":" + domianPort; Hashtable<String, String> env = new Hashtable<>(); DirContext ctx; env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.PROVIDER_URL, url); env.put(Context.SECURITY_PRINCIPAL, userName); env.put(Context.SECURITY_CREDENTIALS, password); try { ctx = new InitialDirContext(env); ctx.close(); return true; } catch (Exception e) { return false; } } }
ShareAuthenticationToken
import org.aaa.dto.User; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.authority.AuthorityUtils; /**
* Created by yfyuan on 2017/3/16.
*/ public class ShareAuthenticationToken extends AbstractAuthenticationToken { private User user; public ShareAuthenticationToken(User user) { super(AuthorityUtils.NO_AUTHORITIES); this.user = user; } @Override public Object getCredentials() { return null; } @Override public Object getPrincipal() { return user; } @Override public void setDetails(Object details) { this.user = (User) details; } }
CustomAuthenticationDetailsSource
import org.springframework.security.authentication.AuthenticationDetailsSource; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; @Component public class CustomAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> { @Override public WebAuthenticationDetails buildDetails(HttpServletRequest context) { return new CustomWebAuthenticationDetails(context); } }
MyAuthenticationProcessingFilter
import org.aaa.constant.RhinocerosConstant; import org.aaa.util.SessionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.UUID; /**
* @Author: songzhen
* @Description: 处理登录sessionId
* @Date: 2020-05-27
*/ public class MyAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter { private static final Logger logger = LoggerFactory.getLogger(MyAuthenticationProcessingFilter.class); protected MyAuthenticationProcessingFilter(String defaultFilterProcessesUrl) { super(defaultFilterProcessesUrl); } public MyAuthenticationProcessingFilter() { super("/loginCheck"); } @Override public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException { return null; } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { /**
* 处理共享session ,建立起admin和sessionId关系
*/ String username = req.getParameter("username"); String uri = ((HttpServletRequest) req).getRequestURI(); if (username != null && !"".equals(username) && uri != null && uri.contains("login")) { /**
* 生成会话id
*/ String token = username + "_" + System.currentTimeMillis() + "_" + UUID.randomUUID(); Cookie cookieInfo = new Cookie(RhinocerosConstant.userToken, token); cookieInfo.setPath("/"); cookieInfo.setMaxAge(129600); ((HttpServletResponse) res).addCookie(cookieInfo); logger.info("login user: {} ", token); SessionUtil.setSessionId(username, token); } super.doFilter(req, res, chain); } }
LocalSecurityFilter
import com.alibaba.fastjson.JSONObject; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import org.apache.commons.lang.StringUtils; import org.aaa.base.SessionMeta; import org.aaa.constant.RhinocerosConstant; import org.aaa.dto.User; import org.aaa.dto.UserVo; import org.aaa.security.ShareAuthenticationToken; import org.aaa.util.SessionUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.core.context.SecurityContext; import org.springframework.security.core.context.SecurityContextHolder; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.concurrent.TimeUnit; /**
* Created by yfyuan on 2017/2/22.
*/ public class LocalSecurityFilter implements Filter { private final static Logger logger = LoggerFactory.getLogger(LocalSecurityFilter.class); private static LoadingCache<String, String> sidCache = CacheBuilder.newBuilder().expireAfterAccess(1, TimeUnit.MINUTES).build(new CacheLoader<String, String>() { @Override public String load(String key) { return null; } }); private static String sessionUrl = null; public static void put(String sid, String uid) { sidCache.put(sid, uid); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { /**
* 获取共享session start
*/ Boolean isLogin = Boolean.FALSE; if (sessionUrl == null) { sessionUrl = (String) DefaultAuthenticationService.strCacheMap.get(RhinocerosConstant.sessionUrl); } /**
* 改用session共享 start
*/ String seesionId = null; String res = null; try { seesionId = SessionUtil.getSessionId((HttpServletRequest) servletRequest); if (seesionId != null) { if (DefaultAuthenticationService.sessionCacheMap.get(seesionId) != null) { if ((System.currentTimeMillis() - DefaultAuthenticationService.sessionCacheMap.get(seesionId).getTimeflag()) <= 500) { //合法时间 User user = DefaultAuthenticationService.sessionCacheMap.get(seesionId).getUser(); DefaultAuthenticationService.sessionCacheMap.put(seesionId, new SessionMeta(System.currentTimeMillis(), user)); Object loginuserContext = ((HttpServletRequest) servletRequest).getSession().getAttribute("SPRING_SECURITY_CONTEXT"); if (loginuserContext == null) { SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(new ShareAuthenticationToken(user)); ((HttpServletRequest) servletRequest).getSession().setAttribute("SPRING_SECURITY_CONTEXT", context); } isLogin = Boolean.TRUE; } else { //没有缓存 res = SessionUtil.get(sessionUrl, seesionId); if (res != null && !"".equals(res)) { JSONObject res0 = JSONObject.parseObject(res); if (res0.getBoolean(RhinocerosConstant.status)) { UserVo uservo = JSONObject.parseObject(JSONObject.parseObject(res).getString("val"), UserVo.class); if (uservo != null) { User user0 = new User(uservo.getUsername(), "", new ArrayList<>()); user0.setUserId(uservo.getUserId()); user0.setUserType(uservo.getUserType()); user0.setUserDepartmentType(uservo.getUserDepartmentType()); DefaultAuthenticationService.sessionCacheMap.put(seesionId, new SessionMeta(System.currentTimeMillis(), user0)); User user = new User(user0.getUsername(), "", new ArrayList<>()); user.setUserId(user0.getUserId()); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(new ShareAuthenticationToken(user)); ((HttpServletRequest) servletRequest).getSession().setAttribute("SPRING_SECURITY_CONTEXT", context); isLogin = Boolean.TRUE; } } } } } else { //没有缓存 res = SessionUtil.get(sessionUrl, seesionId); if (res != null && !"".equals(res)) { JSONObject res0 = JSONObject.parseObject(res); if (res0.getBoolean(RhinocerosConstant.status)) { UserVo uservo = JSONObject.parseObject(JSONObject.parseObject(res).getString("val"), UserVo.class); if (uservo != null) { User user0 = new User(uservo.getUsername(), "", new ArrayList<>()); user0.setUserId(uservo.getUserId()); user0.setUserType(uservo.getUserType()); user0.setUserDepartmentType(uservo.getUserDepartmentType()); DefaultAuthenticationService.sessionCacheMap.put(seesionId, new SessionMeta(System.currentTimeMillis(), user0)); User user = new User(user0.getUsername(), "", new ArrayList<>()); user.setUserId(user0.getUserId()); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(new ShareAuthenticationToken(user)); ((HttpServletRequest) servletRequest).getSession().setAttribute("SPRING_SECURITY_CONTEXT", context); isLogin = Boolean.TRUE; } } } } //todo 增加容错,如果session查询不到,看看缓存中是否存在,并且在有效期内,观察一段时间可以考虑优化 if (!isLogin) { logger.error("不应该进来的 not welcome sessionId:{} ,res={}", seesionId, res); if (DefaultAuthenticationService.sessionCacheMap.get(seesionId) != null) { if ((System.currentTimeMillis() - DefaultAuthenticationService.sessionCacheMap.get(seesionId).getTimeflag()) <= 3600 * 1000) { //合法时间 User user = DefaultAuthenticationService.sessionCacheMap.get(seesionId).getUser(); DefaultAuthenticationService.sessionCacheMap.put(seesionId, new SessionMeta(System.currentTimeMillis(), user)); Object loginuserContext = ((HttpServletRequest) servletRequest).getSession().getAttribute("SPRING_SECURITY_CONTEXT"); if (loginuserContext == null) { SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(new ShareAuthenticationToken(user)); ((HttpServletRequest) servletRequest).getSession().setAttribute("SPRING_SECURITY_CONTEXT", context); } isLogin = Boolean.TRUE; } } } } } catch (Exception e) { logger.error("会话异常 filter exception sessionId:{} ,res={}", seesionId, res, e); } if (!isLogin && ((HttpServletRequest) servletRequest).getServletPath().contains("starter.html") && !((HttpServletRequest) servletRequest).getServletPath().contains(".do")) { servletResponse.setContentType("text/html;charset=UTF-8"); servletResponse.setCharacterEncoding("UTF-8"); PrintWriter out = servletResponse.getWriter(); out.println("<html>"); out.println("<script>"); out.println("window.location.href='/login.do'"); out.println("</script>"); out.println("</html>"); out.flush(); out.close(); ((HttpServletRequest) servletRequest).getSession().setAttribute("SPRING_SECURITY_CONTEXT", null); logger.error("拦截 filter refuse sessionId:{} ,res={}, path={}", seesionId, res, ((HttpServletRequest) servletRequest).getServletPath()); } if (((HttpServletRequest) servletRequest).getServletPath().contains("j_spring_cas_security_logout")) { //login out seesionId = SessionUtil.getSessionId((HttpServletRequest) servletRequest); if (seesionId != null) { //String ip = SessionUtil.getRemoteAddr((HttpServletRequest) servletRequest); SessionUtil.set(sessionUrl, seesionId, null); DefaultAuthenticationService.sessionCacheMap.remove(seesionId); //SessionUtil.set(sessionUrl, ip, null); } logger.info("loginout sessionId:{} ,res={}, path={}", seesionId, res, ((HttpServletRequest) servletRequest).getServletPath()); } //end if ("/render.html".equals(((HttpServletRequest) servletRequest).getServletPath())) { String sid = servletRequest.getParameter("sid"); try { String uid = sidCache.get(sid); if (StringUtils.isNotEmpty(uid)) { User user = new User("shareUser", "", new ArrayList<>()); user.setUserId(sidCache.get(sid)); SecurityContext context = SecurityContextHolder.getContext(); context.setAuthentication(new ShareAuthenticationToken(user)); ((HttpServletRequest) servletRequest).getSession().setAttribute("SPRING_SECURITY_CONTEXT", context); } } catch (Exception e) { //e.printStackTrace(); } } filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
AuthenticationService
public interface AuthenticationService { User getCurrentUser(); }
CustomWebAuthenticationDetails
import org.springframework.security.web.authentication.WebAuthenticationDetails; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public class CustomWebAuthenticationDetails extends WebAuthenticationDetails { private static final long serialVersionUID = -1736970031835448943L; private final HttpSession session; public CustomWebAuthenticationDetails(HttpServletRequest request) { super(request); session = request.getSession(); } public HttpSession getSession() { return session; } }
User
import org.springframework.security.core.GrantedAuthority; public class User extends org.springframework.security.core.userdetails.User { private String userId; private String company; private String department; private String name; private Integer userType; private String userDepartmentType; private String roleName; public User(String username, String password, Collection<? extends GrantedAuthority> authorities) { super(username, password, authorities); } public User(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } }
import org.springframework.jdbc.core.RowMapper; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; public class DbUserDetailService extends JdbcDaoImpl { @Override protected List<UserDetails> loadUsersByUsername(final String username) { return this.getJdbcTemplate().query(super.getUsersByUsernameQuery(), new String[]{username}, new RowMapper() { @Override public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException { String userId = rs.getString(1); String username = rs.getString(2); String loginName = rs.getString(3); String password = rs.getString(4); boolean enabled = rs.getBoolean(5); int userType = rs.getInt(6); String userDepartmentType = rs.getString(7); User user = new User(loginName, password, enabled, true, true, true, AuthorityUtils.NO_AUTHORITIES); user.setUserId(userId); user.setName(username); user.setUserType(userType); user.setUserDepartmentType(userDepartmentType); return user; } }); } @Override protected UserDetails createUserDetails(String username, UserDetails userFromUserQuery, List<GrantedAuthority> combinedAuthorities) { return userFromUserQuery; } }
本文地址:https://blog.csdn.net/lonelymanontheway/article/details/108842855
上一篇: Netty入门这一篇就够了
下一篇: 在 XSL/XSLT 中实现随机排序