Search code examples
javasecurityspring-bootspring-securityspring-security-oauth2

Customize auth error from Spring Security using OAuth2


I was wondering if I could customize the following authorization error:

{
  "error": "unauthorized",
  "error_description": "Full authentication is required to access this resource"
}

I get it when the user request does not have permissions. And I would like to customize it to be quite similar than Spring Boot error:

{
 "timestamp":1445441285803,
 "status":401,
 "error":"Unauthorized",
 "message":"Bad credentials",
 "path":"/oauth/token"
}

Could it be possible?

Many thanks.


Solution

  • I got it :)

    https://stackoverflow.com/a/37132751/2520689

    I need to create a new class which implements "AuthenticationEntryPoint" as the following:

    public class AuthExceptionEntryPoint implements AuthenticationEntryPoint
    {
        @Override
        public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException arg2) throws IOException, ServletException
        {
            final Map<String, Object> mapBodyException = new HashMap<>() ;
    
            mapBodyException.put("error"    , "Error from AuthenticationEntryPoint") ;
            mapBodyException.put("message"  , "Message from AuthenticationEntryPoint") ;
            mapBodyException.put("exception", "My stack trace exception") ;
            mapBodyException.put("path"     , request.getServletPath()) ;
            mapBodyException.put("timestamp", (new Date()).getTime()) ;
    
            response.setContentType("application/json") ;
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED) ;
    
            final ObjectMapper mapper = new ObjectMapper() ;
            mapper.writeValue(response.getOutputStream(), mapBodyException) ;
        }
    }
    

    And add it to my ResourceServerConfigurerAdapter implementation:

    @Configuration
    @EnableResourceServer
    public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter
    {   
        @Override
        public void configure(HttpSecurity http) throws Exception
        {
            http.exceptionHandling().authenticationEntryPoint(new AuthExceptionEntryPoint()) ;
    
        }
    }
    

    You can find my GitHub project which implements everything you need:

    https://github.com/pakkk/custom-spring-security