简体   繁体   English

如何在 Spring 引导应用程序中的请求 Scope Bean 中设置值

[英]How to Set Values in a Request Scope Bean in Spring Boot Application

In my application I want to create a request scoped Bean for storing logged in user details and instantiate it from inside my JWT token verification filter since I'm already querying the record there.在我的应用程序中,我想创建一个请求范围的 Bean,用于存储登录的用户详细信息,并从我的 JWT 令牌验证过滤器中实例化它,因为我已经在那里查询记录。 But, I don't know what is the best way to do it.但是,我不知道最好的方法是什么。 One option I have to directly update values of the bean, but not sure if that's a good approach.一种选择是我必须直接更新 bean 的值,但不确定这是否是一种好方法。

@Bean
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public AppUser loggedInUserDetails() {
   return new AppUser();
}

Request Filter:请求过滤器:

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
    final String authorizationHeader = request.getHeader("Authorization");

    String username = null;
    String jwt = null;

    if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
        jwt = authorizationHeader.substring(7);
        username = jwtUtil.extractUsername(jwt);
    }

    if (username != null) {
        UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
        // Here I want to update the bean
        .....
    }
    chain.doFilter(request, response);
}

If there is any better way to instantiate this bean then please suggest.如果有任何更好的方法来实例化此 bean,请提出建议。

I'm using Spring Boot v2.4.2我正在使用 Spring Boot v2.4.2

If you want to add some logic on the JWT (like denying invalid requests and things like that) the only viable solution is the one you propose, if you don't care about doing that things you could also have the request injected into the bean and read it directly into the bean如果你想在 JWT 上添加一些逻辑(比如拒绝无效请求和类似的东西)唯一可行的解决方案是你提出的那个,如果你不关心做那些事情你也可以将请求注入 bean并将其直接读入 bean

As you probably know just add正如您可能知道的那样,只需添加

private @Autowired HttpServletRequest request;

and reuse the code you now use in the filter并重用您现在在过滤器中使用的代码

bye再见

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM