预授权错误处理 [英] PreAuthorize error handling

查看:125
本文介绍了预授权错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Spring Oauth2Spring Pre-post AnnotationsSpring-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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆