小编典典

如何在Spring Boot中找出当前登录的用户?

spring-boot

在此Spring Boot应用程序中,有一个Web服务,该服务为登录的用户返回一些数据:

@RequestMapping("/resource")
public Map<String, Object> home() {
    Map<String, Object> model = new HashMap<String, Object>();
    model.put("id", UUID.randomUUID().toString());
    model.put("content", "Hello World");
    return model;
}

想象一下,该方法的返回值取决于当前登录的用户。

我如何找出使用该方法登录的用户?


阅读 2528

收藏
2020-05-30

共1个答案

小编典典

按要求:

内部使用SpringSecurity的 SpringBoot提供了一个SecurityContextHolder类,该类允许通过以下方式查找当前经过身份验证的用户:

Authentication auth = SecurityContextHolder.getContext().getAuthentication();

该认证实例现在提供了以下方法:

  • 获取登录用户的用户名: getPrincipal()
  • 获取通过身份验证的用户的密码: getCredentials()
  • 获取已认证用户的分配角色: getAuthorities()
  • 获取经过身份验证的用户的更多详细信息: getDetails()
2020-05-30