springsecurity中的相关配置如下
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(new UnauthorizedEntryPoint())
.and().csrf().disable()
.authorizeRequests().antMatchers("/sys/faceLogin/**").permitAll()
.anyRequest().authenticated()
.and().logout(logout -> logout.deleteCookies("JSESSIONID")).logout().logoutUrl("/sys/logout")
.addLogoutHandler(new TokenLogoutHandler()).and()
.addFilter(tokenLoginFilter)
.addFilter(faceLoginFilter)
.addFilter(concurrentSessionFilter)
.cors().configurationSource(corsConfigurationSource()).and()
.sessionManagement().sessionAuthenticationStrategy(authenticationStrategy);
}
其中,tokenLoginFilter和faceLoginFilter是2个登录的过滤器。 相关的bean配置如下
@Bean
public HttpSessionEventPublisher httpSessionEventPublisher() {
return new HttpSessionEventPublisher();
}
@Bean
public SessionRegistry sessionRegistry(){
return new SessionRegistryImpl();
}
@Bean
public ConcurrentSessionFilter concurrentSessionFilter(SessionRegistry sessionRegistry){
return new ConcurrentSessionFilter(sessionRegistry);
}
@Bean
public AuthenticationManager myAuthenticationManager() throws Exception {
return authenticationManager();
}
@Bean
public TokenLoginFilter tokenLoginFilter(CompositeSessionAuthenticationStrategy strategy,AuthenticationManager authenticationManager){
return new TokenLoginFilter(authenticationManager,strategy,userService);
}
@Bean
public FaceLoginFilter faceLoginFilter(CompositeSessionAuthenticationStrategy strategy,AuthenticationManager authenticationManager){
return new FaceLoginFilter(userService,faceLoginService, strategy,authenticationManager);
}
@Bean
public ConcurrentSessionControlAuthenticationStrategy controlAuthenticationStrategy(SessionRegistry sessionRegistry){
ConcurrentSessionControlAuthenticationStrategy strategy = new ConcurrentSessionControlAuthenticationStrategy(sessionRegistry);
strategy.setMaximumSessions(1);
return strategy;
}
@Bean
public SessionFixationProtectionStrategy sessionFixationProtectionStrategy(){
return new SessionFixationProtectionStrategy();
}
@Bean
public RegisterSessionAuthenticationStrategy registerSessionAuthenticationStrategy(SessionRegistry sessionRegistry){
return new RegisterSessionAuthenticationStrategy(sessionRegistry);
}
@Bean
public CompositeSessionAuthenticationStrategy sessionAuthenticationStrategy(List<SessionAuthenticationStrategy> authenticationStrategies){
return new CompositeSessionAuthenticationStrategy(authenticationStrategies);
}
其中,strategy.setMaximumSessions(1);实现了一个用户只能在一个地方登录系统,不能在多个地方同时登录。 登录过滤器的代码如下
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
private AuthenticationManager authenticationManager;
private IUserService userService;
public TokenLoginFilter(AuthenticationManager authenticationManager, SessionAuthenticationStrategy strategy, IUserService userService) {
this.authenticationManager = authenticationManager;
this.userService=userService;
this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/sys/login","POST"));
super.setSessionAuthenticationStrategy(strategy);
super.setAuthenticationManager(authenticationManager);
}
@SneakyThrows
@Override
public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
throws AuthenticationException {
Map map = new ObjectMapper().readValue(req.getInputStream(), Map.class);
String mobile = (String) map.get("mobile");
String password = (String) map.get("password");
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(mobile, password));
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
SecurityUser securityUser = (SecurityUser) authResult.getPrincipal();
User user=new User().setId(securityUser.getId()).setLevel(securityUser.getLevel());
List<GrantedAuthority> authorities = userService.getPermsByUser(user).stream()
.filter(permission -> permission.getType() == PermissionConstants.PY_API)
.map(permission -> new SimpleGrantedAuthority(permission.getCode()))
.collect(Collectors.toList());
SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(securityUser,securityUser.getId(),authorities));
ResponseUtil.out(response,Result.SUCCESS().setData(request.getSession().getId()));
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response,
AuthenticationException e) throws IOException, ServletException {
ResponseUtil.out(response, new Result(ResultCode.MOBILE_OR_PASSWORD_ERROR));
}
}
其他具体配置细节详见官方文档 Session Management
|