ale*_*oid 2 java spring spring-mvc spring-security spring-boot
在我的Spring Boot应用程序中,我具有以下Web安全配置:
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.headers().frameOptions().disable()
.and()
.antMatcher("/**").authorizeRequests()
.antMatchers("/actuator/health").permitAll()
.antMatchers("/actuator/**").hasAuthority(Authority.Type.ROLE_ADMIN.getName())
.antMatchers("/login/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login")
.failureUrl("/login?error").permitAll()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login?logout")
.and()
.csrf().csrfTokenRepository(csrfTokenRepository()).ignoringAntMatchers("/login/**")
.and()
.addFilterBefore(corsFilter, ChannelProcessingFilter.class)
.addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class)
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class)
.exceptionHandling().authenticationEntryPoint(new Http403ForbiddenEntryPoint());
// @formatter:on
}
....
}
Run Code Online (Sandbox Code Playgroud)
和ControllerAdvice:
@ControllerAdvice
public class GlobalControllerExceptionHandler {
private static final String ERROR = "error";
@ExceptionHandler(value = Exception.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public Map<String, ErrorResponse> handleException(Exception exception) {
return createResponseError(exception);
}
private Map<String, ErrorResponse> createResponseError(Exception exception) {
final Map<String, ErrorResponse> responseError = new HashMap<String, ErrorResponse>();
responseError.put(ERROR, new ErrorResponse(exception.getMessage()));
return responseError;
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我试图由匿名用户访问我的安全API网址时,我收到以下错误:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri May 06 22:59:05 EEST 2016
There was an unexpected error (type=Forbidden, status=403).
Access Denied
Run Code Online (Sandbox Code Playgroud)
而不是此页面,我需要处理我的此类错误ControllerAdvice(以便返回JSON错误响应),该错误对于所有其他异常(但仅对经过身份验证的用户)有效。
我该如何处理此身份验证/授权错误GlobalControllerExceptionHandler?
ControllerAdvices用于辅助Controller类,ExceptionHandlers用于处理Controllers 引发的异常。AuthenticationException和AccessDeniedExceptions通常由AbstractSecurityInterceptorSpring Security 抛出。因此,我猜测您将无法AuthenticationException使用ControllerAdvices 捕获这些,因为ExceptionTranslationFilter已经捕获了它们并将其转换为适当的HTTP响应。
更好的方法是exceptionHandling在您的计算机中使用WebSecurityConfigurerAdapter。使用它,您可以配置AuthenticationEntryPoint和AccessDeniedHandler。在这里,我返回一个403 Forbidden用于拒绝访问的情况和一个401 Unauthorized缺少身份验证令牌的情况:
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.accessDeniedHandler((request, response, accessDeniedException) -> {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
})
.authenticationEntryPoint((request, response, authException) -> {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
});
}
}
Run Code Online (Sandbox Code Playgroud)
使用exceptionHandling您可以配置ExceptionTranslationFilter为使用accessDeniedHandler处理AccessDeniedExceptionS和authenticationEntryPoint为AuthenticationException秒。窥视一下ExceptionTranslationFilter以获得对该过程的更多了解。
如果您不喜欢:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri May 06 22:59:05 EEST 2016
There was an unexpected error (type=Forbidden, status=403).
Access Denied
Run Code Online (Sandbox Code Playgroud)
并且想要对其进行自定义,您应该提供的实现ErrorController并返回Map<String, ErrorResponse>for错误。
| 归档时间: |
|
| 查看次数: |
5046 次 |
| 最近记录: |