首页 > 解决方案 > 有没有办法从 Spring Security 中获取 UserId?

问题描述

我想从 Spring Security 中获取用户 ID,目前我找到了这个解决方案:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
   String username = ((UserDetails) principal).getUsername();
   User user = userRepository.findAllByUsername(username);

}

然后使用该 user.getId() 方法.. 有没有内置的方法可以让我更轻松地获取 ID?或者我可以修改我的 UserDetailsS​​ervice 以包含 ID?

我对这个框架很陌生。我读到使用另一个存储库可能会有所帮助,但我不想为了这个目的而使用另一个存储库。

标签: javaspring-security

解决方案


据我了解,您主要关心的是不是每次需要登录用户的 ID 时都重复此代码?如果是这种情况,只需将此代码移至某个服务,例如 UserService:

    @Service
    public class UserService {
         public User getLoggedInUser(long id) {
             // your code from original post goes here
         }
    }

然后将此服务包含在课程中。您打算使用此功能并使用它。假设你的类被称为是一种名为 MyController 的 RestController:

@RestController
public class MyController{
    private UserService userService;

    public MyController(UserService userService){
        this.userService = userService;
    }

    public void myMethod() {
        User authUser = userService.getLoggedInUser();
    }
}

或者如果您只需要 ID,请将方法更改为返回 ID 并改用它:

long userId = userService.getLoggedInUserId();

新 UserService 方法中的代码与您上面的问题中的代码相同,但在 MyController 中使用它的代码将更具可读性。

如果您只需要此 ID 来检查权限,请考虑使用@PreAuthorize("hasRole('ROLE_SMTH')")Spring Security 或其他类似的注释。


推荐阅读