英文:
Spring Security returns 403 instead of 401 and creates invalid Redis session cookie
问题
我正在使用Spring Security和Spring Data Redis来跟踪具有自定义角色和权限的用户会话。当我尝试在浏览器中访问一个需要预授权的端点但没有会话cookie时,它应该返回401错误。然而实际情况是会创建一个新的(无效的)会话cookie,并且该端点返回403错误。
这是我的SecurityConfig:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests((authorize) -> authorize.anyRequest().authenticated())
.csrf().disable().cors();
}
}
我还在使用MethodSecurityConfig
和UserDetails
的实现来解析用户认证中的自定义字段。
英文:
I'm using Spring Security and Spring Data Redis to keep track of user sessions with custom roles and entitlements. When I try to hit a PreAuthorized endpoint without a session cookie in my browser, it should return a 401. Instead a new (invalid) session cookie is created and the endpoint returns a 403.
Here's my SecurityConfig:
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests((authorize) -> authorize.anyRequest().authenticated())
.csrf().disable().cors();
}
}
I'm also using MethodSecurityConfig
and an implementation of UserDetails
to parse the custom fields from the user authentication.
答案1
得分: 1
这是修复方法,适用于将来遇到类似问题的人:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and()
.csrf().disable().cors().and()
.requestCache().disable().exceptionHandling().and()
.authorizeRequests().anyRequest().authenticated().and()
.exceptionHandling().authenticationEntryPoint(
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
}
英文:
Here's the fix, for anyone who encounters a similar issue down the line:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.NEVER).and() //let redis handle session creation
.csrf().disable().cors().and()
.requestCache().disable().exceptionHandling().and() //prevent exception creating duplicate session
.authorizeRequests().anyRequest().authenticated().and() //all endpoints need auth
.exceptionHandling().authenticationEntryPoint(
new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)); //return 401 on no session
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论