Popular Posts

Saturday, February 6, 2016

Unauthorized Entry Point with Spring Security


Let's say you already have secured your app with spring security but now every time a request comes in and you are not able to authenticate the user and the web server returns a 403 Forbidden exception instead of 401 Unauthorized exception, weird right! Well that's the default behaviour which is not correct logically because:

HTTP 401 Unauthorized Exception is for authentication, means the user is not authenticated by the app, the app doesn't know who the user is, it might be because of bad/missing credentials or wrong username or whatever else but in short the user is not authenticated, so please try again.

HTTP 403 Forbidden Exception is for the protected resource, means the user is authenticated user but he doesn't have the right privileges to access the resource so either ask your administrator to give you the privileges or forget about it simple.

Summarizing above, a 401 Unauthorized response should be used for missing or bad authentication, and a 403 Forbidden response should be used after authenticating the user, so the user is authenticated but isn’t authorized to perform the requested operation on a given resource.

Code:

1:  public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {  
2:    
3:    @Override  
4:    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {  
5:    
6:      //log statement if you want to log it to server logs.  
7:      response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User Authentication cannot be verified, Please log in again with your credentials");  
8:    
9:    }  
10:  }  

Now you need to register this entry point in your spring security web configurer class, like this :

1:  http.exceptionHandling().authenticationEntryPoint(new UnauthorizedEntryPoint());  

Please comment, if you have any questions or concerns.