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

查看:549
本文介绍了如何找到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 Security 提供了 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()

  • Get the username of the logged in user: getPrincipal()
  • Get the password of the authenticated user: getCredentials()
  • Get the assigned roles of the authenticated user: getAuthorities()
  • Get further details of the authenticated user: getDetails()

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

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