Java 如果我手动设置身份验证,则原则的自动注入将为空

Java 如果我手动设置身份验证,则原则的自动注入将为空,java,spring-security,Java,Spring Security,我正在尝试在自己的登录控制器中自定义登录过程,而不是使用UsernamePasswordAuthenticationFilter @PostMapping(value=“/login”) 公共响应登录( HttpServletRequest httpRequest, @RequestBody AuthenticationRequest AuthenticationRequest){ //这里是认证码 Authentication=this.authenticationManager.authen

我正在尝试在自己的登录控制器中自定义登录过程,而不是使用UsernamePasswordAuthenticationFilter

@PostMapping(value=“/login”)
公共响应登录(
HttpServletRequest httpRequest,
@RequestBody AuthenticationRequest AuthenticationRequest){
//这里是认证码
Authentication=this.authenticationManager.authenticate(authRequest);
SecurityContext上下文=SecurityContextHolder.getContext();
setAuthentication(身份验证);
返回handlerAuthLogin(httpRequest、result、authorizationRequest);
}
但如果我按以下方式登录成功,则无法在其他控制器中自动注入主体:

@控制器
公共类用户控制器{
@请求映射(value=“/me”)
公共字符串getMyName(主体){
返回principal.getName();//principal为null
}
}

有人知道为什么要修复它吗?

当您执行
上下文时。setAuthentication(authentication)
该验证仅对当前请求有效。因此,对于第二个
/me
请求,您还需要设置身份验证。 因此,您需要根据每个请求对用户进行身份验证。这可以通过实现一个
通用过滤器bean来实现:

公共类CustomAuthenticationFilter扩展了GenericFilterBean{
私人最终身份验证经理AuthenticationManager;
公共CustomAuthenticationFilter(
AuthenticationManager(AuthenticationManager){
this.authenticationManager=authenticationManager;
}
@凌驾
公共无效doFilter(ServletRequest-req、ServletResponse-resp、FilterChain链)
抛出IOException、ServletException{
HttpServletRequest请求=(HttpServletRequest)请求;
HttpServletResponse=(HttpServletResponse)resp;
/* 
请注意,您现在需要以不同的方式接收身份验证令牌。
通常会使用标题来进行此操作。
*/
Authentication=authenticationManager.authenticate(request.getHeader(“authToken”);
SecurityContext上下文=SecurityContextHolder.getContext().setAuthentication(身份验证);
链式过滤器(请求、响应);
}
}
在实现过滤器之后,您需要在servlet容器中最适合它的位置注册它。Spring Security根据
WebSecurityConfigure
处理安全过滤器,因此您需要在用户的相应配置程序的配置中注册过滤器

例如,我将其放在
ConcurrentSessionFilter
之后:

@配置
@订单(1)
公共静态类UserWebSecurity扩展了WebSecurity配置适配器{
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
CustomAuthenticationFilter=new PlayerAuthenticationFilter(jwtService,
对象映射器);
http.addFilterAfter(过滤器,ConcurrentSessionFilter.class);
(...)
}
}
查看有关文档,以找到最适合您的方法的位置

使现代化 我写了一篇关于这个话题的更深入的文章。我可以自由地查看它。

@Marcus

谢谢你的澄清,我找到了我的理由

我错误地配置了一个

公共类WebSecurity配置扩展了WebSecurity配置适配器{
公共网站安全配置(){
super(true);//我禁用了默认配置,因此默认情况下没有添加SecurityContextPersistenceFilter,并且我的所有SecurityContext信息都不是持久的
}
}

很高兴听到你解决了这个问题。请记住,在对话中不应使用任何答案。这就是像这样的评论的目的。别忘了接受一个既能解决你的问题又能帮助你解决问题的答案。这将奖励帮助过你的人,并为其他访问此问题的人提供一个更容易的方向。