Spring Security

Spring Boot 3.1.3 + Spring Security 6.1.3 BasicAuthenticationFilter设置了UsernamePasswordAuthenticationToken,访问的时候获取的SecurityContextHolder.getContext().getAuthentication()值为null

有哪位可以帮忙解决下吗

SecurityFilterChain filterChain

img

JwtAuthenticationFilter extends BasicAuthenticationFilter设置UsernamePasswordAuthenticationToken

img

获取的SecurityContextHolder.getContext().getAuthentication()是null

img

项目结构是单体多模块方式,auth为security模块

img

根据您提供的信息,问题可能出在认证和授权的流程中。Spring Security的BasicAuthenticationFilter会对请求进行身份验证,并将认证信息存储在SecurityContext中。然而,如果SecurityContextHolder.getContext().getAuthentication()返回null,这可能意味着身份验证失败或尚未完成。

以下是一些可能的问题和解决方法:

  1. 认证信息未正确配置:请确保您的Spring Boot和Spring Security配置正确,并且UsernamePasswordAuthenticationToken被正确地设置。
  2. 认证过滤器未正确配置:请确保BasicAuthenticationFilter在Spring Security的过滤器链中被正确配置。
  3. SecurityContextHolder未正确配置:请确保SecurityContextHolder的线程绑定正确。这可以通过在应用程序上下文中设置一个Bean来完成,例如:
@Bean
public SecurityContextHolderStrategy securityContextHolderStrategy() {
    return new ThreadLocalSecurityContextHolderStrategy();
}
  1. 异步方法中获取认证信息:如果您的代码在异步方法中调用SecurityContextHolder.getContext().getAuthentication(),您可能会遇到问题,因为异步方法的上下文可能不包含SecurityContext。在这种情况下,您需要使用Authentication对象的其他方法来获取认证信息。

请根据您的具体情况检查上述问题,并尝试相应的解决方法。如果问题仍然存在,请提供更多的代码和配置信息,以便我们更好地帮助您解决问题。

看下ExceptionTranslationFilter第216行