spring 如何从JWT或请求中获取用户ID?[已关闭]

dddzy1tm  于 2023-04-19  发布在  Spring
关注(0)|答案(1)|浏览(223)

已关闭,此问题需要更focused,目前不接受回答。
**要改进此问题吗?**更新问题,使其仅关注editing this post的一个问题。

7天前关闭
Improve this question
在我的Sping Boot 应用程序(假设它是博客应用程序)中,我使用JWT身份验证。
如果我想创建一个新的帖子,我应该在请求体中传递用户ID吗?但是这样做是不安全的。因为,我应该将用户ID存储在前端的本地存储中,并在发送之前将其放入请求中。
或者我应该从JWT获得用户ID?但是,我必须在所有控制器中注入authManager依赖项?

n3h0vuf2

n3h0vuf21#

是的,您应该从JWT令牌获取userId
令牌需要在所有请求中添加,并且在后台执行任何操作之前必须进行验证。
你不必将AuthManager添加到所有的控制器中。你可以使用Spring-Security设置规则。看看这个:https://spring.io/guides/topicals/spring-security-architecture/
最后:你可以只在需要用户名的地方注入AuthManager。或者让Spring添加Authentication。

public class YourController {

   @POST
   public void create(@RequestBody Post post, Authentication auth) {
      // from the auth you can extract the users name or id
   }
}

相关问题