java - 有没有办法从 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?或者我可以修改我的 UserDetailsService 以包含 ID?
我对这个框架很陌生。我读到使用另一个存储库可能会有所帮助,但我不想为了这个目的而使用另一个存储库。
解决方案
据我了解,您主要关心的是不是每次需要登录用户的 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 或其他类似的注释。
推荐阅读
- c# - ListView 使用向上和向下按钮移动项目 .NET Framework
- android - AR图像识别从原生开发到跨平台
- docker - docker container ls --size 不准确,如何获得准确的容器大小?
- angular - 带有视图模型前缀 (vm) 的 Angular 8 UI 模型绑定
- tfs - 将文件夹检入 TFS 服务器后从 TFS 中删除
- python - 从 python 控制台清除多行
- python - 让 Python 程序运行另一个 Python 程序并让它们同时运行?
- javascript - Electron 桌面应用程序在它应该是离线应用程序时尝试 TCP 连接
- java - 如何断言对象列表具有一组具有特定值的属性
- c# - 使用 EPPlus 将 Web 表单 DataGrid 导出到 excel