spring-security - AuthenticationException 会发生什么情况?

标签 spring-security spring-boot

我有一个启用了 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/

相关文章:

mysql - Spring Boot 2.0.x 上的 InnoDB?

java - Spring security UserDetails服务配置

java - 使用 Java 检查 Elasticsearch 部署当前是否可用

java - 如何将 Tomcat 重写阀添加到 Spring Boot 2.0 应用程序

java - 无法使用 spring boot 渲染 thymeleaf

java - Spring boot 和 GCP - 使用 spring-cloud-gcp-starter-sql-postgresql 连接 Cloud SQL 实例尝试 SSL,但启动延迟

java - 强制 Spring 安全性在帐户状态标志之前检查凭据

带有过滤器 permitAll 的 Spring Security 不起作用

java - 尝试向我的 Spring Web Flow2 项目添加安全性

spring - BadCredentialsException : Kerberos validation not succesfull