如何在 Spring Boot 中找出当前登录的用户? [英] How to find out the currently logged-in user in Spring Boot?

查看:144
本文介绍了如何在 Spring Boot 中找出当前登录的用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个Spring Boot 应用程序 有一个 web 服务,它为登录用户返回一些数据:

In this Spring Boot application there is a web service, which returns some data for a logged-in user:

@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;
}

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

Imagine, the return value of the method depends on what user is currently logged in.

我怎样才能知道哪个用户是用那个方法登录的?

How can I find out, which user is logged in in that method?

推荐答案

根据要求:

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

Spring Boot which uses Spring Security internally provides a SecurityContextHolder class which allows the lookup of the currently authenticated user via:

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

身份验证 实例现在提供以下方法:

The authentication instance now provides the following methods:

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

这篇关于如何在 Spring Boot 中找出当前登录的用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆