gpt4 book ai didi

java - 如果我手动设置身份验证,原理的自动注入(inject)将为空

转载 作者:行者123 更新时间:2023-12-01 06:01:51 27 4
gpt4 key购买 nike

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

 @PostMapping(value = "/login")
public ResponseEntity<?> login(
HttpServletRequest httpRequest,
@RequestBody AuthenticationRequest authenticationRequest) {
// authentication code here
Authentication authenticate=this.authenticationManager.authenticate(authRequest);
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(authentication);
return handlerAuthLogin(httpRequest, result, authorizationRequest);
}

但是如果我登录成功,我无法在其他 Controller 中自动注入(inject)Principal,如下所示:

@Controller
public class UsersController {

@RequestMapping(value = "/me")
public string getMyName(Principal principal){
return principal.getName(); // principal is null
}
}

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

最佳答案

当您执行context.setAuthentication(authentication)时,身份验证仅对当前请求有效。因此,对于第二个 /me 请求,您还需要设置身份验证。因此,您需要根据每个请求对用户进行身份验证。这可以通过实现 GenericFilterBean 来完成:

public class CustomAuthenticationFilter extends GenericFilterBean {

private final AuthenticationManager authenticationManager;

public CustomAuthenticationFilter(
AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {

HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;

/*
Note that you need to receive the authentication token in different manner now.
Usually headers are used for that.
*/
Authentication authenticate = authenticationManager.authenticate(request.getHeader("authToken"));
SecurityContext context = SecurityContextHolder.getContext().setAuthentication(authentication);

chain.doFilter(request, response);
}
}

实现过滤器后,您需要将其注册到 servlet 容器中最适合的位置。 Spring Security 根据 WebsecutiryConfigurer 处理安全过滤器,因此您需要在用户相应配置器的配置中注册过滤器。

作为示例,我将其放在 ConcurrentSessionFilter 之后:

@Configuration
@Order(1)
public static class UserWebSecurity extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
CustomAuthenticationFilter filter = new PlayerAuthenticationFilter(jwtService,
objectMapper);

http.addFilterAfter(filter, ConcurrentSessionFilter.class);

(...)
}

}

查看有关 filter ordering 的文档找到最适合您的方法的位置。

更新

我写了一篇更深入的blog post关于这个话题。有空去看看。

关于java - 如果我手动设置身份验证,原理的自动注入(inject)将为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55992894/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com