我注意到,当使用自定义安全过滤器登录后,jsessionid不会改变。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
public UsernamePasswordAuthenticationFilter authenticationFilter() throws Exception {
CustomFilter customFilter = new CustomFilter();
customFilter.setAuthenticationManager(authenticationManagerBean());
return customFilter;
}
即使我把 sessionManagement().sessionFixation().newSession()
但当我删除自定义过滤器时,jesessionid确实会在每次登录和注销时重新设置。
有人知道为什么吗?我想了解。
自定义筛选器具有相同的实现 UsernamePasswordAuthenticationFilter
```
public class CustomFilter extends UsernamePasswordAuthenticationFilter {
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
if (!request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
} else {
String username = this.obtainUsername(request);
String password = this.obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
this.setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
}
}
我根据本指南构建了一个简单的项目:https://spring.io/guides/gs/securing-web/
1条答案
按热度按时间qgelzfjb1#
简单的回答是默认的
SessionAuthenticationStrategy
在里面UsernamePasswordAuthenticationFilter
是一个NullAuthenticatedSessionStrategy
.通过简单地扩展
UsernamePasswordAuthenticationFilter
在创建新示例时,自定义筛选器将使用NullAuthenticatedSessionStrategy
.当spring security创建
UsernamePasswordAuthenticationFilter
从表单登录配置中,它设置SessionAuthenticationStrategy
到中配置的策略HttpSecurity
,默认为ChangeSessionIdAuthenticationStrategy
.如果您跟踪代码,您可以看到这是如何发生的。
配置时
http.formLogin()
SpringSecurity创建了一个FormLoginConfigurer
延伸AbstractAuthenticationFilterConfigurer
.这个
FormLoginConfigurer
构造函数创建的新示例UsernamePasswordAuthenticationFilter
.后来,当
configure
方法在FormLoginConfigurer
,您会注意到过滤器上设置了各种属性,其中之一是SessionAuthenticationStrategy
.如果你看
SessionManagementConfigurer
,您会注意到默认策略是ChangeSessionIdAuthenticationStrategy
.这个
SessionAuthenticationStrategy#onAuthentication
后来在doFilter
方法UsernamePasswordAuthenticationFilter
.这就是为什么spring security配置的过滤器在登录后会更改会话id,而没有设置属性的过滤器的新示例不会更改会话id的原因。