[英]How to find out the currently logged-in user in 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;
}
想象一下,该方法的返回值取决于当前登录的用户。
我怎样才能知道哪个用户登录了该方法?
按要求:
内部使用Spring Security 的Spring Boot 提供了一个SecurityContextHolder类,它允许通过以下方式查找当前经过身份验证的用户:
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
身份验证实例现在提供以下方法:
getPrincipal()
getCredentials()
getAuthorities()
getDetails()
从 Spring Security 3.2 开始,您可以通过在控制器方法中添加参数来获取当前登录的用户(您的UserDetails
实现):
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal;
@RequestMapping("/resource")
public Map<String, Object> home(@AuthenticationPrincipal User user) {
..
}
将User
替换为实现UserDetails
接口的类的名称。
编辑:
由于 Spring Security 4.0 注释被移动到一个不同的包:
import org.springframework.security.core.annotation.AuthenticationPrincipal;
附录:
即使在WebFlux
反应式环境中,这也可以工作,而SecurityContextHolder.getContext().getAuthentication()
由于范式从每个请求模型的线程转移到每个线程的多个请求而不起作用。
您也可以简单地使用 HttpServletRequest 来获取用户原则,
使用 HttpServletRequest 请求,
String user=request.getUserPrincipal().getName();
一种方法是将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;
}
从 5.2 版开始,您可以使用CurrentSecurityContext注释:
@GetMapping("/hello")
public String hello(@CurrentSecurityContext(expression="authentication?.name")
String username) {
return "Hello, " + username + "!";
}
在 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"));
最近使用 Keycloak 身份验证服务器并访问当前登录的用户数据可以这样访问
String userID;
KeycloakPrincipal kcPrincipal = getPrincipal();
KeycloakSecurityContext ksContext = kcPrincipal.getKeycloakSecurityContext();
IDToken idToken = ksContext.getToken();
userID = idToken.getName();
我使用带有 OAuth 的 spring boot 2.0 所以我这样做
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Object pricipal = auth.getPrincipal();
String user="";
if (pricipal instanceof DefaultOidcUser) {
user = ((DefaultOidcUser) pricipal).getName();
}
您可以在不使用任何 spring 安全功能的情况下找到当前登录的用户名。 您只需要一个 jdk 1.8
请执行下列操作 :
@RequestMapping("/login")
@Override
public ModelAndView AuthChecker(@RequestParam("email") String email, @RequestParam("password") String password, Customers cust) {
ModelAndView mv = new ModelAndView("index");
if((repo.findByEmail(email)!=null) && (repo.findByPassword(password)!=null)) {
List<Customers> l= repo.findAll();
cust = (Customers) l.stream()
.filter(x -> email.equals(x.getEmail()))
.findAny()
.orElse(null);
mv.addObject("user",cust.getName());
mv.setViewName("DashBoardRedirect");
return mv;
成功获取名称后,您可以在任何 jsp/thymeleaf 视图中使用相同的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.