Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Customise Error Handling in JWT Authentication with Spring Security 6?

I have implemented a simple resource server with Spring Boot using the following dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
    <version>2.4.12</version>
</dependency>

Most of my requirements are satisfied with the built-in, default workflow. However, it would be nice if I could customise the error handling part.

Currently, when I make an unauthorised request, I just get a blank response with a 401 status code.

enter image description here

Instead of an empty response with just a 401 code, I want to send custom error messages like "Invalid access token", "Access token missing", "Access token expired", etc. It would help a lot while debugging.

I have tried implementing the interfaces AuthenticationEntryPoint and AuthenticationFailureHandler. But, I haven't been successful.

I have referred the following article from the Spring Security docs:

https://docs.spring.io/spring-security/reference/servlet/oauth2/resource-server/jwt.html

Also, this is my Web Security Configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeHttpRequests((authz) -> authz
                        .requestMatchers("/public/**").permitAll()
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }

}

Can someone provide a way to customise error messages in the JWT Authentication workflow?

like image 785
Kunal Nk Avatar asked Dec 11 '25 00:12

Kunal Nk


2 Answers

Maybe not what you're looking for but the error response is in the headers.

See Bearer Token Failure.

enter image description here

like image 162
K.Nicholas Avatar answered Dec 13 '25 14:12

K.Nicholas


If you wish to customize only auth failure response you can do it using the following code

 @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
// your configuration 
                .exceptionHandling(exceptionHandling -> exceptionHandling
                        .accessDeniedHandler(new CustomAccessDeniedHandler())
                        .authenticationEntryPoint(new CustomAuthenticationEntryPoint()))

the above code adds custom exception handlers for authorization and authentication respectively

you should implement CustomAuthenticationEntryPoint (AuthenticationEntryPoint) and CustomAccessDeniedHandler (AccessDeniedHandler, see AccessDeniedHandlerImpl )

example for implementation of AuthenticationEntryPoint and return any message that you desire in case of auth failure

@Slf4j
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest,
                         HttpServletResponse httpServletResponse,
                         AuthenticationException e) throws IOException, ServletException {
        log.info("Responding with unauthorized error. Message - {}", e.getMessage());
    enter code here
        httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                e.getLocalizedMessage()); //or replace with response.getWriter() and return anything you desire
    }

One thing to keep in mind: it is considered a good practice to return a uniform response and error code for both authentication (401) and authorization (403) failures.

This will make attacker work harder since it would be harder to determine the cause of failure. server log prints should be more informative and specify the exact issue.

like image 38
ezer Avatar answered Dec 13 '25 14:12

ezer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!