【问题标题】:Spring Security returns 403 instead of 401 and creates invalid Redis session cookieSpring Security 返回 403 而不是 401 并创建无效的 Redis 会话 cookie
【发布时间】:2021-01-28 21:58:49
【问题描述】:

我正在使用 Spring Security 和 Spring Data Redis 来跟踪具有自定义角色和权利的用户会话。当我尝试在浏览器中访问没有会话 cookie 的 PreAuthorized 端点时,它应该返回 401。相反,会创建一个新的(无效)会话 cookie,并且端点会返回 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();
    }
}

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

【问题讨论】:

  • 添加AuthenticationFailureHandler并将响应状态编辑为401 baeldung.com/…
  • @RoieBeck 谢谢你,但没用。在调试模式下运行后端时,我在故障处理程序中放置了一个断点,但它没有到达它。
  • 只要确保您在经过验证后添加了这一行:.failureHandler(authenticationFailureHandler());
  • @RoieBeck yessir

标签: java spring spring-boot spring-security spring-data-redis


【解决方案1】:

以下是解决方案,适用于遇到类似问题的任何人:

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

【讨论】:

    猜你喜欢
    • 2015-08-19
    • 2021-07-28
    • 2015-08-16
    • 2017-03-21
    • 2019-09-18
    • 2018-08-15
    • 2017-09-12
    • 2015-10-23
    • 2018-08-28
    相关资源
    最近更新 更多