PreAuthorize error handling

好久不见. 提交于 2019-12-03 14:57:08

问题


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


回答1:


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();
}



回答2:


Implement 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();
    }
}

SomeJsonModel will be your own POJO/model class which you can control And add that access denied handler in 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());
    }

`



来源:https://stackoverflow.com/questions/28410690/preauthorize-error-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!