简体   繁体   中英

How to catch AccessDeniedException in Spring Boot REST API

I have a simple Spring Boot REST API with 2 endpoints, one is protected one is not. For the one is protected, I want to catch the AccessDeniedException and send a 401 rather than the default 500 error. Here is my security configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

@Override
public void configure(WebSecurity webSecurity) {
    webSecurity.ignoring().antMatchers("/");
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .exceptionHandling()
            .accessDeniedHandler(new AccessDeniedHandler() {
                @Override
                public void handle(HttpServletRequest request, HttpServletResponse response, org.springframework.security.access.AccessDeniedException accessDeniedException) throws IOException, ServletException {
                    System.out.println("I am here now!!!");
                }
            });

    http
            .addFilterAfter(getSecurityFilter(), FilterSecurityInterceptor.class);
    http
            .sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http
            .csrf()
            .disable();
    http
            .authorizeRequests()
            .antMatchers("/protected").anonymous();
}

public Filter getSecurityFilter() {
    return new Filter() {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            //do nothing here
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            String appKeyHeaderValue = ((HttpServletRequest)request).getHeader("X-AppKey");
            if(appKeyHeaderValue!=null && appKeyHeaderValue.equals("MY_KEY")) {
                chain.doFilter(request,response);
            } else {
                throw new AccessDeniedException("Access denied man");
            }
        }

        @Override
        public void destroy() {

        }
    };
}

}

I never see my I am here now!!! print statement, what I instead see is the default page Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Tue Jul 25 23:21:15 CDT 2017 There was an unexpected error (type=Internal Server Error, status=500). Access denied man Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Tue Jul 25 23:21:15 CDT 2017 There was an unexpected error (type=Internal Server Error, status=500). Access denied man Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Tue Jul 25 23:21:15 CDT 2017 There was an unexpected error (type=Internal Server Error, status=500). Access denied man Notice how my Access denied man does get printed from when the exception is being thrown.

When I run the project, I also see the following in the console: 2017-07-25 23:21:14.818 INFO 3872 --- [ restartedMain] swsmmaRequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2017-07-25 23:21:14.818 INFO 3872 --- [ restartedMain] swsmmaRequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)

Here is how my project structure looks like:

在此处输入图片说明

I use a custom class extending ResponseEntityExceptionHandler with some annotations.

You just need to create a Class like this:

@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(AccessDeniedException.class)
    public final ResponseEntity<ErrorMessage> handleAccessDeniedException(AccessDeniedException ex, WebRequest request) {
        ErrorMessage errorDetails = new ErrorMessage(new Date(), ex.getMessage(), request.getDescription(false));
        return new ResponseEntity<>(errorDetails, HttpStatus.FORBIDDEN);
    }

}

In this case the answer will be something like:

{
    "timestamp": "2018-12-28T14:25:23.213+0000",
    "message": "Access is denied",
    "details": "uri=/user/list"
}

As suggested by @Afridi exception occurs before it even reaches controllers, so it has to be handled in filter chain. I suggest to do the following :

public class AccessDeniedExceptionFilter extends OncePerRequestFilter {

    @Override
    public void doFilterInternal(HttpServletRequest req, HttpServletResponse res, 
                                FilterChain fc) throws ServletException, IOException {
        try {
            fc.doFilter(request, response);
        } catch (AccessDeniedException e) {
         // log error if needed here then redirect
     RequestDispatcher requestDispatcher = 
             getServletContext().getRequestDispatcher(redirecturl);
     requestDispatcher.forward(request, response);

    }
}

Add this filter to filter chain in

protected void configure(HttpSecurity http) throws Exception {
http
....
.addFilterAfter(httpClientFilter(), AccessDeniedExceptionFilter.class)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM