如何在Spring Boot REST API中捕获AccessDeniedException

时间:2017-07-26 04:43:05

标签: spring security spring-boot

我有一个带有2个端点的简单Spring Boot REST API,其中一个是受保护的,而不是。对于受保护的人,我想捕获AccessDeniedException并发送401而不是默认的500错误。这是我的安全配置:

@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 am here now!!!打印语句,我看到的是默认页面 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 请注意我的Access denied man是如何在抛出异常时打印出来的。

当我运行项目时,我还在控制台中看到以下内容: 2017-07-25 23:21:14.818 INFO 3872 --- [ restartedMain] s.w.s.m.m.a.RequestMappingHandlerMapping : 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] s.w.s.m.m.a.RequestMappingHandlerMapping : 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)

以下是我的项目结构:

enter image description here

2 个答案:

答案 0 :(得分:2)

正如@Afridi所建议的那样,异常在它到达控制器之前发生,所以它必须在过滤器链中处理。我建议做以下事情:

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

    }
}

将此过滤器添加到

中的过滤器链
protected void configure(HttpSecurity http) throws Exception {
http
....
.addFilterAfter(httpClientFilter(), AccessDeniedExceptionFilter.class)

答案 1 :(得分:0)

我使用自定义类扩展ResponseEntityExceptionHandler并添加一些注释。

您只需要创建一个这样的类:

@ControllerAdvice
@RestController
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);
    }

}

在这种情况下,答案将类似于:

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