spring-security 将Spring Security更改为在身份验证失败时返回401

vbopmzt1  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(173)

在我的Sping Boot (v. 2.7.0)应用程序中,我使用Spring Security进行身份验证。如果用户试图使用无效的凭据登录,服务器将以403(禁止)状态代码响应,但我希望使用401(未授权)。
我在配置中找不到任何指示SpringSecurity的默认行为已被覆盖的内容,但无论是否已被覆盖,我都希望在身份验证失败时返回401。
我逐步执行了相关的SpringSecurity代码,当身份验证失败时,似乎会调用SpringSecurity方法SimpleUrlAuthenticationFailureHandler.onAuthenticationFailure

response.sendError(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());

但是由于某种原因,403被返回到客户端-所以我猜响应在上面的行之后被改变了。

**如何更改Spring Security以在身份验证失败时返回401?**我在下面提供了我的安全配置以供参考。

@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, jsr250Enabled = true)
public class SecurityConfiguration {

    @Autowired
    private AuthenticationConfiguration authenticationConfiguration;

    @Bean
    public SecurityFilterChain configure(HttpSecurity http) throws Exception {
        AuthenticationManager authenticationManager = authenticationConfiguration.getAuthenticationManager();
        var jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager);

        var jwtAuthorisationFilter = new JwtAuthorisationFilter();

        http.cors().and().csrf().disable().authorizeRequests()
            .anyRequest().authenticated().and()
            .addFilter(jwtAuthenticationFilter)
            .addFilterAfter(jwtAuthorisationFilter, BasicAuthenticationFilter.class)
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        return http.build();
    }
}

JwtAuthenticationFilter会呼叫authenticationManager.authenticate,如果认证无效,则会掷回org.springframework.security.authentication.BadCredentialsException

更新

我尝试添加一个自定义的AuthenticationFailureHandler bean,如this article中所述,但是我的自定义bean从未被调用(而是调用了默认bean SimpleUrlAuthenticationFailureHandler)。

anhgbhbe

anhgbhbe1#

您可以提供自己的自定义AccessDeniedHandler实现。

@Bean
public SecurityFilterChain configure(HttpSecurity http) throws Exception {
    AuthenticationManager authenticationManager = authenticationConfiguration.getAuthenticationManager();
    var jwtAuthenticationFilter = new JwtAuthenticationFilter(authenticationManager);

    var jwtAuthorisationFilter = new JwtAuthorisationFilter();

    http.cors().and().csrf().disable().authorizeRequests()
        .anyRequest().authenticated().and()
        .addFilter(jwtAuthenticationFilter)
        .addFilterAfter(jwtAuthorisationFilter, BasicAuthenticationFilter.class)
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .exceptionHandling()
        .accessDeniedHandler( (request, response, exception) ->
             response.sendError(HttpStatus.UNAUTHORIZED.value(), exception.getMessage()
        ));

    return http.build();
}

相关问题