Spring-security-oauth: How could I customize the authorization error json?

Created on 31 Aug 2017  路  5Comments  路  Source: spring-projects/spring-security-oauth

Hello,

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.

Regards,
Paco.

waiting-for-triage

Most helpful comment

Hi @pakkk ,

You can customize all your exceptions attributes thrown as json by overriding the default attributes like below :

@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            Throwable error = getError(requestAttributes);
            // of course you can customize any exception ( e.g : bad requests )
            if(error instanceof AccessDeniedException){
                errorAttributes.clear();
                errorAttributes.put("error", "unauthorized");
                errorAttributes.put("error_description", "Full authentication is required to access this resource");
            }
         return errorAttributes;
        }
    };
}

hope this help

All 5 comments

@pakkk you might want to have a look at https://github.com/zalando/problem-spring-web which has support for Problem JSON error responses for Spring Web MVC (incl. Spring Security related errors)

Hi @pakkk ,

You can customize all your exceptions attributes thrown as json by overriding the default attributes like below :

@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {
        @Override
        public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes, boolean includeStackTrace) {
            Map<String, Object> errorAttributes = super.getErrorAttributes(requestAttributes, includeStackTrace);
            Throwable error = getError(requestAttributes);
            // of course you can customize any exception ( e.g : bad requests )
            if(error instanceof AccessDeniedException){
                errorAttributes.clear();
                errorAttributes.put("error", "unauthorized");
                errorAttributes.put("error_description", "Full authentication is required to access this resource");
            }
         return errorAttributes;
        }
    };
}

hope this help

@duergner I think this issue is to close

Agree

Excuse me, are you the problem solved

Was this page helpful?
0 / 5 - 0 ratings