Search code examples
javaspringspring-securityspring-boot

Spring Security anonymous 401 instead of 403


I have a problem with default behaviour in spring security with authorize requests provided with Java Config.

http
       ....
       .authorizeRequests()
          .antMatchers("/api/test/secured/*").authenticated()

When I do a call to for example /api/test/secured/user without login (with anonymous user), it returns 403 Forbidden. Is there an easy way to change status to 401 Unauthorized when anonymous user wants to get secured by authenticated() or @PreAuthorize resource?


Solution

  • I've got solution here:

    http
       .authenticationEntryPoint(authenticationEntryPoint)
    

    AuthenticationEntryPoint source code:

    @Component
    public class Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint {
    
        private final Logger log = LoggerFactory.getLogger(Http401UnauthorizedEntryPoint.class);
    
        /**
         * Always returns a 401 error code to the client.
         */
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException,
                ServletException {
    
            log.debug("Pre-authenticated entry point called. Rejecting access");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access Denied");
        }
    }