我有一个简单的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)
这是我的项目结构:
exceptionResolvers.add(new CustomHandlerExceptionResolver());
} - jishnu radhakrishnan