Search code examples
authenticationspring-securityauthorization

difference between EntryPoint and handler in Spring Security


In Spring Security, when it comes to authentication, AuthenticationExeption occurs, and I know that logic such as redirection is performed through AuthenticationEntryPoint. And Authorization exception throws AccessDeniedException and AccessDeniedHandler handles it.

However, both of these are objects that are responsible for processing logic for specific exceptions, so I don't know why they are created as objects with different names, EntryPoint and Handler. The function to override when inheriting EntryPoint and the function to implement when inheriting Handler are even the same form.

public interface AuthenticationEntryPoint {

void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
        throws IOException, ServletException;

}

public interface AccessDeniedHandler {

void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException)
        throws IOException, ServletException;

}

Why does Spring Security not handle exceptions with a single object called handler, but separate Entrypoint objects? I'm curious about the difference between the two.


Solution

  • Two different names for two different uses cases:

    • entrypoint: if you are not logged in (authentication)
    • access denied: if you are not allowed to access a ressource (authorization)

    See Spring Security Reference:

    Handling Security Exceptions

    The ExceptionTranslationFilter allows translation of AccessDeniedException and AuthenticationException into HTTP responses.

    ExceptionTranslationFilter is inserted into the FilterChainProxy as one of the Security Filters.

    The following image shows the relationship of ExceptionTranslationFilter to other components:

    enter image description here

    1. First, the ExceptionTranslationFilter invokes FilterChain.doFilter(request, response) to invoke the rest of the application.

    2. If the user is not authenticated or it is an AuthenticationException, then Start Authentication.

      • The SecurityContextHolder is cleared out.

      • The HttpServletRequest is saved so that it can be used to replay the original request once authentication is successful.

      • The AuthenticationEntryPoint is used to request credentials from the client. For example, it might redirect to a log in page or send a WWW-Authenticate header.

    3. Otherwise, if it is an AccessDeniedException, then Access Denied. The AccessDeniedHandler is invoked to handle access denied.

    If the application does not throw an AccessDeniedException or an AuthenticationException, then ExceptionTranslationFilter does not do anything.