How to Handle Security Exception in Spring Framework
@ControllerAdvice to catch exceptions like AccessDeniedException or AuthenticationException. You can also customize Spring Security's AccessDeniedHandler and AuthenticationEntryPoint to control responses when security errors occur.Why This Happens
Security exceptions in Spring occur when a user tries to access a resource they are not allowed to or when authentication fails. For example, if a user without the right role tries to access a protected page, Spring Security throws an AccessDeniedException. If the user is not logged in, an AuthenticationException may be thrown.
If these exceptions are not handled, the user sees a default error page or a stack trace, which is not user-friendly.
import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SampleController { @GetMapping("/admin") public String adminPage() { // Simulate access denied throw new AccessDeniedException("You are not allowed to access this page"); } }
The Fix
To handle security exceptions gracefully, create a class with @ControllerAdvice and add methods annotated with @ExceptionHandler for specific exceptions. This lets you return friendly messages or custom error pages.
Alternatively, configure Spring Security's AccessDeniedHandler and AuthenticationEntryPoint to customize responses for access denied and authentication failures.
import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.access.AccessDeniedHandler; import org.springframework.security.web.AuthenticationEntryPoint; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @ControllerAdvice public class SecurityExceptionHandler { @ExceptionHandler(AccessDeniedException.class) @ResponseStatus(HttpStatus.FORBIDDEN) @ResponseBody public String handleAccessDenied(AccessDeniedException ex) { return "Access denied: " + ex.getMessage(); } @ExceptionHandler(AuthenticationException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseBody public String handleAuthenticationException(AuthenticationException ex) { return "Authentication failed: " + ex.getMessage(); } } @Component public class CustomAccessDeniedHandler implements AccessDeniedHandler { @Override public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().write("Custom Access Denied Message: " + accessDeniedException.getMessage()); } } @Component public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); response.getWriter().write("Custom Authentication Required: " + authException.getMessage()); } }
Prevention
To avoid unhandled security exceptions, always configure exception handling in your Spring Security setup. Use @ControllerAdvice for global exception handling and customize AccessDeniedHandler and AuthenticationEntryPoint beans.
Test your security rules regularly and provide clear user feedback on authorization failures. Keep your Spring Security version updated to benefit from the latest fixes and features.
Related Errors
- AuthenticationCredentialsNotFoundException: Happens when no authentication info is found; fix by ensuring security context is set.
- InsufficientAuthenticationException: Occurs when authentication is incomplete; fix by requiring full authentication before access.
- InvalidCsrfTokenException: Happens when CSRF token is missing or invalid; fix by enabling CSRF protection properly.