在项目中加入 Spring Security 后,它会将所有的错误状态码覆盖为 403,例如 400, 405 和 500,我们也可能需要将 403 改为 401 作为未登录的状态码。本文将介绍如何自定义 AuthenticationEntryPoint 以解决此问题。
背景情况
- 我根据这个视频配置了基础的 Spring Security 和 JWT 鉴权:
解决方案
将 exceptionHandling
添加到 SecurityFilterChain
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import lombok.RequiredArgsConstructor; import org.springframework.http.HttpStatus; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.authentication.HttpStatusEntryPoint;
@Configuration @EnableWebSecurity @EnableMethodSecurity @RequiredArgsConstructor public class AuthConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .exceptionHandling( exceptionHandling -> exceptionHandling .accessDeniedHandler( (request, response, accessDeniedException) -> response .sendError(HttpStatus.UNAUTHORIZED.value()) ) .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED)) return http.build(); } }
|