Spring security AuthenticationException会发生什么情况?

Spring security AuthenticationException会发生什么情况?,spring-security,spring-boot,Spring Security,Spring Boot,我有一个启用了spring安全性的spring引导应用程序。我有一个自定义的AbstractPreAuthenticatedProcessingFilter,它检查请求头中外部系统设置的一些身份验证令牌。如果令牌不存在或无效,相应的AuthenticationManager将抛出AuthenticationException。看起来很简单 我的问题是,我希望能够通过回复403(禁止)状态来处理此AuthenticationException。我怎么做?我尝试将以下内容添加到WebSecurity

我有一个启用了spring安全性的spring引导应用程序。我有一个自定义的AbstractPreAuthenticatedProcessingFilter,它检查请求头中外部系统设置的一些身份验证令牌。如果令牌不存在或无效,相应的AuthenticationManager将抛出AuthenticationException。看起来很简单

我的问题是,我希望能够通过回复403(禁止)状态来处理此AuthenticationException。我怎么做?我尝试将以下内容添加到WebSecurity配置适配器:


但它不起作用。问题是,假设(如果我理解正确的话)处理这些事情的ExceptionTranslationFilter是默认安全筛选器链中的最后一个筛选器,抛出的异常永远不会到达它。我完全卡住了。这是怎么回事?请帮忙

很久以前,你的问题已经解决了,但我被困在同一个问题中,没有解决方案,所以我决定解释如何解决这个问题

您可以编辑筛选器链,您可以在预验证筛选器之前放置一个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。

您需要从筛选器手动发送403响应。或者更好——您可以为过滤器提供入口点实现。这样就可以将用户转发到登录页面。当你说“它不工作”时,你的确切意思是什么?抛出异常后会发生什么,您确定它是在筛选器链的正确部分抛出的吗?异常(Authenticationexception的子类)是从我的AuthenticationManager的“Authentication”方法中抛出的。但它永远不会得到ExceptionTranslationFilter,因此对它没有特殊处理。关于“过滤链的正确部分”——这就是我的问题的实质。AbstractPreAuthenticatedProcessingFilter位于筛选器链中ExceptionTranslationFilter之前。这让我很困惑,因为这意味着从它抛出的异常不会被ExceptionTranslationFilter捕获。
    if ( !StringUtils.hasText(request.getParameter("MY_TOKEN")) ) {
        throw new BadCredentialsException("No pre-authenticated principal found in request");
    }