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

在此Spring Boot" title="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;

}

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

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

回答:

按要求:

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

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

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

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

以上是 如何在Spring Boot中找出当前登录的用户? 的全部内容, 来源链接: utcz.com/qa/436039.html

回到顶部