Spring Security 自定义状态码,防止正常状态码被 403 覆盖

在项目中加入 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();
}
}

Spring Security 自定义状态码,防止正常状态码被 403 覆盖
https://blog.zhanganzhi.com/zh-CN/2023/07/2d4f8ccace6c/
作者
Andy Zhang
发布于
2023年7月5日
许可协议