Spring Boot HandBook

    Introduction :#

    Spring Security provides robust exception handling mechanisms to manage various security-related exceptions that can occur during authentication and authorization processes.

    By understanding and handling these exceptions, you can improve the security of your application and provide clear, informative feedback to users when authentication or authorization fails. In Spring Security, managing these exceptions effectively is key to maintaining a secure and user-friendly application.

    Here's an overview of key concepts and techniques for handling exceptions in Spring Security:

    1. Common Exceptions:

    AuthenticationException:

    AuthenticationException contains several exceptions, Use HttpStatus 401 – UnAuthorized to handle the response: • AccountExpiredException • BadCredentialsException • CredentialsExpiredException • AuthenticationCredentialsNotFoundException • SessionAuthenticationException

    JwtException:

    JwtException contains several exceptions, Use HttpStatus 401 – UnAuthorized to handle the response: • ExpiredJwtException • MalformedJwtException • SignatureException • UnsupportedJwtException • IllegalArgumentException

    1. Handling Authentication Exceptions
    import io.jsonwebtoken.JwtException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.core.AuthenticationException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice // public class GlobalExceptionHandler { // to handle specific exceptions // Handle a specific exception (e.g., ResourceNotFoundException) @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ApiError> handleResourceNotFoundException(ResourceNotFoundException exception){ //It creates an ApiError object with a message and a 404 Not Found status, returning it as the response. ApiError apiError = new ApiError(exception.getLocalizedMessage(), HttpStatus.NOT_FOUND); return new ResponseEntity<>(apiError,HttpStatus.NOT_FOUND); } // Handle a specific exception (e.g., AuthenticationException) @ExceptionHandler(AuthenticationException.class) public ResponseEntity<ApiError> handleAuthenticationException(AuthenticationException e){ //It returns an ApiError with a message and a 401 Unauthorized status. ApiError apiError = new ApiError(e.getLocalizedMessage(), HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(apiError,HttpStatus.UNAUTHORIZED); } // Handle a specific exception (e.g., JwtException) @ExceptionHandler(JwtException.class) public ResponseEntity<ApiError> handleJwtException(JwtException e){ //It returns an ApiError with a message and a 401 Unauthorized status. ApiError apiError = new ApiError(e.getLocalizedMessage(), HttpStatus.UNAUTHORIZED); return new ResponseEntity<>(apiError,HttpStatus.UNAUTHORIZED); } } //Each method creates a custom ApiError object that provides the client with clear and helpful error messages, along with the appropriate HTTP status code. import lombok.Data; import org.springframework.http.HttpStatus; import java.time.LocalDateTime; @Data public class ApiError { private LocalDateTime timeStamp; private String error; private HttpStatus status; public ApiError() { this.timeStamp = LocalDateTime.now(); } public ApiError(String error, HttpStatus statusCode) { this(); this.error = error; this.status = statusCode; } }

    @RestControllerAdvice combined with a GlobalExceptionHandler allows you to centralize exception handling in a Spring Boot application. This setup ensures that your application can catch and handle exceptions in a consistent way across all controllers. @RestControllerAdvice is a specialization of @ControllerAdvice that applies to all controllers annotated with @RestController. It allows you to handle exceptions globally. The GlobalExceptionHandler is the class where you define how different types of exceptions should be handled. It’s typically a class annotated with @RestControllerAdvice.

    Last updated on Dec 09, 2024