roy*_*oyB 22 spring spring-security spring-annotations spring-boot spring-security-oauth2
我正在使用Spring Oauth2和Spring Pre-post Annotations使用Spring-boot
我有一个服务班MyService.一个MyService方法是:
@PreAuthorize("#id.equals(authentication.principal.id)")
public SomeResponse getExampleResponse(String id){...}
Run Code Online (Sandbox Code Playgroud)
我能以某种方式控制调用者控制器返回的json吗?
默认返回的json是:
{error : "access_denied" , error_message: ".."}
Run Code Online (Sandbox Code Playgroud)
我希望能够控制error_message参数.我正在寻找类似的东西:
@PreAuthorize(value ="#id.equals(authentication.principal.id)", onError ="throw new SomeException("bad params")")
public SomeResponse getExampleResponse(String id){...}
Run Code Online (Sandbox Code Playgroud)
我想到的一种方法是使用 ExceptionHandler
@ExceptionHandler(AccessDeniedException.class)
public Response handleAccessDeniedException(Exception ex, HttpServletRequest request){
...
}
Run Code Online (Sandbox Code Playgroud)
但我无法控制message异常.而且我不能确定这Exception将在未来的版本中被抛出
有关错误处理的Spring Boot文档:http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-error-handling.控制JSON的一种方法是添加一个@Bean类型ErrorAttributes.
@Bean
ErrorAttributes errorAttributes() {
return new MyErrorAttributes();
}
Run Code Online (Sandbox Code Playgroud)
实现AccessDeniedHandler
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try {
ObjectMapper mapper = new ObjectMapper();
SomeJsonModel jsonResponse =new SomeJsonModel();
mapper.writeValue(response.getOutputStream(), jsonResponse);
} catch (Exception e) {
throw new ServletException();
}
}
Run Code Online (Sandbox Code Playgroud)
SomeJsonModel将是您自己的POJO / model类,您可以控制它并在Resource Server Configuration中添加该访问被拒绝的处理程序
`
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers()
.antMatchers(SECURED_PATTERN).and().authorizeRequests()
.antMatchers(HttpMethod.POST,SECURED_PATTERN).access(SECURED_WRITE_SCOPE)
.anyRequest().access(SECURED_READ_SCOPE).and()
.exceptionHandling().authenticationEntryPoint(newAuthExceptionEntryPoint())
.accessDeniedHandler(new MyAccessDeniedHandler());
}
Run Code Online (Sandbox Code Playgroud)
`
| 归档时间: |
|
| 查看次数: |
8118 次 |
| 最近记录: |