预授权错误处理 [英] PreAuthorize error handling
问题描述
我正在将Spring Oauth2
和Spring Pre-post Annotations
与Spring-boot
一起使用
我有一个服务类别MyService
. MyService
方法之一是:
I Have a service class MyService
. one of MyService
methods is:
@PreAuthorize("#id.equals(authentication.principal.id)")
public SomeResponse getExampleResponse(String id){...}
我可以通过某种方式控制调用方控制器返回的json吗?
can i control in some manner the json that is returned by the caller Controller?
默认返回的json是:
the json that is returned by default is:
{error : "access_denied" , error_message: ".."}
我希望能够控制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){...}
我想到的一种方法是使用ExceptionHandler
One way i thought of doing it is by Using ExceptionHandler
@ExceptionHandler(AccessDeniedException.class)
public Response handleAccessDeniedException(Exception ex, HttpServletRequest request){
...
}
但是我无法控制异常的message
.而且我也不确定此Exception
是否会在将来的版本中抛出
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
推荐答案
关于错误处理的Spring Boot文档:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling .控制JSON的一种方法是添加ErrorAttributes
类型的@Bean
.
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();
}
这篇关于预授权错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!