I'm using Spring Oauth2
and Spring Pre-post Annotations
With Spring-boot
I Have a service class MyService
. one of MyService
methods is:
@PreAuthorize("#id.equals(authentication.principal.id)") public SomeResponse getExampleResponse(String id){...}
can i control in some manner the json that is returned by the caller Controller?
the json that is returned by default is:
{error : "access_denied" , error_message: ".."}
I Want to be able to control the error_message
param. I'm looking for something similar to:
@PreAuthorize(value ="#id.equals(authentication.principal.id)", onError ="throw new SomeException("bad params")") public SomeResponse getExampleResponse(String id){...}
One way i thought of doing it is by Using ExceptionHandler
@ExceptionHandler(AccessDeniedException.class) public Response handleAccessDeniedException(Exception ex, HttpServletRequest request){ ... }
but i can't control the message
of the exception. and also i can't be sure that this Exception
will be thrown in future releases
The @PreAuthorize authorizes on the basis of role or the argument which is passed to the method. The @PostAuthorize checks for authrorisation after method execution. The @PostAuthorize authorizes on the basis of logged in roles, return object by method and passed argument to the method.
The difference between @Secured and @PreAuthorize are as follows : The main difference between @Secured and @PreAuthorize is that @PreAuthorize can work with Spring EL. We can access methods and properties of SecurityExpressionRoot while using @PreAuthorize but not with @Secured.
Exception HandlerThe @ExceptionHandler is an annotation used to handle the specific exceptions and sending the custom responses to the client. Define a class that extends the RuntimeException class. You can define the @ExceptionHandler method to handle the exceptions as shown.
To deal with exceptions, the recommended practice is to follow the sequence outlined below: Determine whether the REST API request succeeded or failed, based on the HTTP status response code returned. If the REST API request failed and the response is application/json, serialize the model.
Spring Boot docs on error handling: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling. One way you can control the JSON is by adding a @Bean
of type ErrorAttributes
.
@Bean ErrorAttributes errorAttributes() { return new MyErrorAttributes(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With