Spring Security customizing status code, and prevent other codes overridden by 403

The Spring Security will override all errors like 400, 405, and 500 to 403, and we may want to use 401 for unauthorized requests. This article will solve this problem by customizing an AuthenticationEntryPoint.

Background

  • I folled this video to setup Spring Security and JWT authorization:

解决方案

Add exceptionHandling to 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 customizing status code, and prevent other codes overridden by 403
https://blog.zhanganzhi.com/en/2023/07/d7099ff451fa/
Author
Andy Zhang
Posted on
July 5, 2023
Licensed under