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

时间:2015-07-01 10:44:15

标签: java spring-boot

this Spring Boot application中有一个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;
}

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

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

8 个答案:

答案 0 :(得分:76)

根据要求:

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

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

authentication实例现在提供以下方法:

  • 获取登录用户的用户名:getPrincipal()
  • 获取经过身份验证的用户的密码:getCredentials()
  • 获取经过身份验证的用户的指定角色:getAuthorities()
  • 详细了解经过身份验证的用户:getDetails()

答案 1 :(得分:10)

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

使用HttpServletRequest请求,

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

答案 2 :(得分:7)

从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;

答案 3 :(得分:4)

从5.2版开始,您可以使用CurrentSecurityContext批注:

@GetMapping("/hello")
public String hello(@CurrentSecurityContext(expression="authentication.name")
                    String username) {
    return "Hello, " + username + "!";
}

答案 4 :(得分:1)

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

String userID;

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

答案 5 :(得分:0)

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

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

答案 6 :(得分:0)

在Spring boot v2.1.9.RELEASE中,如果您尝试获取名称email,given_name,则可以从Pricipal获取这些详细信息。 注意:我正在将Spring Security与google oauth2配合使用

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"));

答案 7 :(得分:-1)

无需使用任何 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视图中使用相同的名称。