我有一个启用了 spring-security 的 spring-boot 应用程序。我有一个自定义的 AbstractPreAuthenticatedProcessingFilter 来检查外部系统设置的某些身份验证 token 的请求 header 。如果 token 不存在或无效,相应的 AuthenticationManager 会抛出 AuthenticationException。看起来很简单。
我的问题是我希望能够通过回复 403(禁止)状态来处理此 AuthenticationException。我该怎么做?我尝试将以下内容添加到WebSecurityConfigurerAdapter:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(new Http403ForbiddenEntryPoint());
...
但它不起作用。问题是 ExceptionTranslationFilter 应该(如果我理解正确的话)处理这些事情是默认安全过滤器链中的最后一个过滤器,而抛出的异常永远不会到达它。我完全被困住了。这应该如何运作?请帮忙!
最佳答案
很久以前你的问题就已经完成了,但我陷入了同样的问题而没有解决,所以我决定解释一下如何解决这个问题。
您可以编辑 FilterChain,您可以在 PreAuthenticationFilter 之前放置一个 ExceptionTranslationFilter 作为...
http
.csrf().disable()
.addFilter(myPreAuthenticationFilter)
.addFilterBefore(new ExceptionTranslationFilter(
new Http403ForbiddenEntryPoint()),
myPreAuthenticationFilter.getClass()
)
.authorizeRequests()
.antMatchers(authSecuredUrls).authenticated()
.anyRequest().permitAll()
.and()
.httpBasic()
.authenticationEntryPoint(new Http403ForbiddenEntryPoint())
;
如果未提供任何凭据,您的 AbstractPreAuthenticatedProcessingFilter getPreAuthenticatedCredentials 或 getPreAuthenticatedPrincipal 方法可能会抛出 AuthenticationException ...
if ( !StringUtils.hasText(request.getParameter("MY_TOKEN")) ) {
throw new BadCredentialsException("No pre-authenticated principal found in request");
}
或者您的 AuthenticationManager 验证方法也可以抛出 AuthenticationException。
关于spring-security - AuthenticationException 会发生什么情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25326860/