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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31159075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:43:41  来源:igfitidea点击:

How to find out the currently logged-in user in Spring Boot?

javaspring-boot

提问by Dmitrii Pisarenko

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

这个 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;
}

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?

我怎样才能知道哪个用户登录了该方法?

采纳答案by Roman Vottner

As per request:

按要求:

Spring Boot which uses Spring Security internallyprovides a SecurityContextHolderclass which allows the lookup of the currently authenticated user via:

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

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

The authenticationinstance now provides the following methods:

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

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

回答by NikhilP

You can simply use HttpServletRequest also to get user principle,

您也可以简单地使用 HttpServletRequest 来获取用户原则,

using HttpServletRequest request,

使用 HttpServletRequest 请求,

String user=request.getUserPrincipal().getName();

回答by David

One way is to add java.security.Principal as a parameter as follows:

一种方法是将 java.security.Principal 添加为参数,如下所示:

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

回答by Petko Mirchev

Im using spring boot 2.0 with OAuth so I'm doing it like this

我使用带有 OAuth 的 spring boot 2.0 所以我这样做

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object pricipal = auth.getPrincipal();
String user="";
if (pricipal instanceof DefaultOidcUser) {
       user = ((DefaultOidcUser) pricipal).getName();
}

回答by NikolaB

Since Spring Security 3.2 you can get currently logged in user (your implementation of UserDetails) by adding a parameter inside your controller method:

从 Spring Security 3.2 开始,您可以UserDetails通过在控制器方法中添加一个参数来获取当前登录的用户(您的实现):

import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;

@RequestMapping("/resource")
public Map<String, Object> home(@AuthenticationPrincipal User user) {
   ..
}

Replace Userwith the name of your class which implements UserDetailsinterface.

替换User为实现UserDetails接口的类的名称。

Edit:

编辑

Since Spring Security 4.0 annotation was moved to a different package:

由于 Spring Security 4.0 注释被移动到一个不同的包:

import org.springframework.security.core.annotation.AuthenticationPrincipal;

Addendum:

附录

This will work even in WebFluxreactive environment versus the SecurityContextHolder.getContext().getAuthentication()which won't work because of paradigm shift from thread per request model to multiple requests per thread.

这甚至在WebFlux反应式环境中SecurityContextHolder.getContext().getAuthentication()也能工作,而后者由于范式从每个请求模型的线程转变为每个线程多个请求而不起作用。

回答by Petko Mirchev

Recently using Keycloak authentication server and accessing currently logged-in user data is accessible like this

最近使用 Keycloak 身份验证服务器并访问当前登录的用户数据可以这样访问

String userID;

KeycloakPrincipal kcPrincipal = getPrincipal();
KeycloakSecurityContext ksContext = kcPrincipal.getKeycloakSecurityContext();
IDToken idToken = ksContext.getToken();
userID = idToken.getName();

回答by Gourav

In Spring boot v2.1.9.RELEASE if you are trying to get the name, email , given_name you can get those details from Pricipal. Note: I am using spring security with google oauth2

在 Spring boot v2.1.9.RELEASE 中,如果您尝试获取姓名、电子邮件、given_name,您可以从 Pricipal 获取这些详细信息。注意:我在 google oauth2 中使用 spring security

Map<String , Object> userDetails = ((DefaultOidcUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getAttributes(); System.out.println(userDetails.get("name")); System.out.println(userDetails.get("email")); System.out.println(userDetails.get("given_name"));

Map<String , Object> userDetails = ((DefaultOidcUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getAttributes(); System.out.println(userDetails.get("name")); System.out.println(userDetails.get("email")); System.out.println(userDetails.get("given_name"));