Spring MVC AccessDeniedException 500 error received instead of custom 401 error for @PreAuthorized unauth requests

放肆的年华 提交于 2019-12-01 05:15:54

OK guys, wasn't able to get any help from the community BUT I did find a solution -- although it's not a direct solution.

@ControllerAdvice
public class SecurityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler({AccessDeniedException.class})
    public ResponseEntity<Object> handleAccessDeniedException(Exception ex, WebRequest request) {
        if(ex.getMessage().toLowerCase().indexOf("access is denied") > -1) {
            return new ResponseEntity<Object>("Unauthorized Access", new HttpHeaders(), HttpStatus.UNAUTHORIZED);
        }

        return new ResponseEntity<Object>(ex.getMessage(), new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

This new file in my app will allow me to control what happens during an exception. Now I can just manually inspect the problem to see if it was "access is denied" and then redirect to 401 which DOES WORK. The problem above was that the code to redirect to the 401 wasn't ever being hit. This code DOES get executed.

Again, this isn't a direct solution as we're manipulating a different piece of Spring MVC and kind of hacking default behavior to get it to work.

If anyone has a more elegant solution, please do post.

I'm assuming you're not using Spring Boot - Might it be that you did not register the springSecurityFilterChain with the container?

The stack trace does not show any Spring Security filters getting called. Your custom AccessDeniedHandler would get called in the ExceptionTranslationFilter that resides in the springSecurityFilterChain. But it seems like your method security interceptor is throwing an AccessDeniedException that isn't getting caught anywhere.

Check out the reference guide.

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