Spring 安全性 returns 403 而不是 401 并创建无效的 Redis 会话 cookie

Spring Security returns 403 instead of 401 and creates invalid Redis session cookie

我正在使用 Spring 安全和 Spring 数据 Redis 来跟踪具有自定义角色和权利的用户会话。当我尝试在我的浏览器中访问一个没有会话 cookie 的预授权端点时,它应该 return 一个 401。而是创建一个新的(无效的)会话 cookie 并且端点 returns 一个 403。

这是我的安全配置:

@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();
    }
}

我还使用 MethodSecurityConfigUserDetails 的实现来解析用户身份验证中的自定义字段。

以下是解决方法,供遇到类似问题的任何人使用:

    @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
    }