Handling exceptions gracefully is crucial in any web application, especially when it comes to security. In a Spring Boot application that uses JWT (JSON Web Tokens) for authentication, you might encounter various exceptions related to token validation. In this guide, we'll show you how to set up a custom exception handler to manage JWT-related exceptions effectively.
Creating the Custom Exception Handler
We'll begin by creating a custom exception handler class called `CustomExceptionHandler`. This class will handle exceptions such as expired tokens or invalid signatures.
package com.ypss.advice;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.ypss.dto.ApiResponseDTO;
import com.ypss.dto.ResponseSadhnaDTO;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.security.SignatureException;
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CustomExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity> handleSecurityException(Exception ex) {
        System.out.println("Exception class: " + ex.getClass().getName());
        ApiResponseDTO apiResponse = new ApiResponseDTO();
        HttpStatus statusCode = HttpStatus.FORBIDDEN;
        
        if(ex instanceof ExpiredJwtException) {
            apiResponse.setStatus(0);
            apiResponse.setMessage("JWT Token is expired");
            apiResponse.setResCode(HttpStatus.FORBIDDEN.value());
            statusCode = HttpStatus.FORBIDDEN;
        } 
        if(ex instanceof SignatureException) {
            apiResponse.setStatus(0);
            apiResponse.setMessage("Invalid JWT Token");
            apiResponse.setResCode(HttpStatus.FORBIDDEN.value());
            statusCode = HttpStatus.FORBIDDEN;
        }
        
        return new ResponseEntity<>(apiResponse, statusCode);
    }
}
    
  
                In this code, we've defined a class annotated with `@RestControllerAdvice` to handle exceptions globally. The `handleSecurityException` method within this class handles various exceptions, including `ExpiredJwtException` and `SignatureException`, which are common JWT-related issues.
Integrating the Custom Exception Handler
To make use of our custom exception handler, we need to integrate it into our Spring Boot application. Here are the steps to follow:
Step 1: Autowire the Exception Resolver
In your `WebSecurityConfiguration.java` file, autowire the `HandlerExceptionResolver`. Add the following code to your configuration class:
@Autowired
@Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver exceptionResolver;    
                Step 2: Create the JWT Request Filter
Create a JWT request filter, typically named `JwtRequestFilter`. This filter will be responsible for intercepting requests and validating JWT tokens. Pass the `exceptionResolver` as a parameter to the filter.
Step 3: Modify the Security Filter Chain
In the `SecurityFilterChain` configuration method, modify the `addFilterBefore` method to include your `JwtRequestFilter`. Here's an example of how to do it:
.addFilterBefore(jwtRequestFilter(), UsernamePasswordAuthenticationFilter.class)
                Step 4: Implement Token Validation
Inside the `doFilterInternal` method of your `JwtRequestFilter`, include token validation logic. If an exception occurs during token validation, it will be caught and handled by our custom exception handler.
try {
    // Token validation logic here
} catch (Exception ex) {
    exceptionResolver.resolveException(request, response, null, ex);
}
                With these steps, you've successfully integrated a custom exception handler for JWT token-related issues in your Spring Boot application.
Now, when JWT-related exceptions occur, your application will respond with informative error messages, enhancing the security and user experience.