Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreAuthorize error handling

Tags:

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

like image 672
royB Avatar asked Feb 09 '15 13:02

royB


People also ask

What is the use of @PreAuthorize?

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.

What is the primary difference between @secured and @PreAuthorize?

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.

How do you handle a spring boot exception?

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.

How do you handle exceptions in REST services?

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.


1 Answers

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(); } 
like image 146
Dave Syer Avatar answered Sep 23 '22 01:09

Dave Syer