PreAuthorize错误处理

roy*_*oyB 22 spring spring-security spring-annotations spring-boot spring-security-oauth2

我正在使用Spring Oauth2Spring 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将在未来的版本中被抛出

Dav*_*yer 9

有关错误处理的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)

  • 嗨@DaveSyer,我的情况是`@PreAuthorize("isAuthenticated()和principal.user.isEnabled()== true和principal.user.isConfirmed()== true")`我希望区别哪些约束抛出AccessDeniedException.然后根据不满意的条件处理它并抛出我自己的异常.或者只有我可以自己编写自己的方面并通过自己的方式抛出异常? (3认同)
  • 感谢您的回答。文档部分不太清楚,如果能有一个关于这个主题的“如何做”就太好了。`DefaultErrorAttributes` 方法:`addErrorDetail` 我如何控制传递给 `ErrorAttributes` 的 `Throwable error` 消息? (2认同)

Abd*_*mon 5

实现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)

`