springsecurity-获取当前用户

springsecurity-获取当前用户

丁起男 157 2022-02-28

springsecurity-获取当前用户

SecurityContext

SecurityContext context = SecurityContextHolder.getContext();
context.getAuthentication().getPrincipal();

Authentication

@GetMapping("demo")
public String demo(Authentication authentication) {
        return authentication.getName();
}

Principal

@GetMapping("demo")
public String demo(Principal principal) {
        return principal.getName();
}

@AuthenticationPrincipal

spring security4.0提供注解

@GetMapping("demo")
 public String demo(@AuthenticationPrincipal User user) {
   return user.getUsername();
}

也可以直接获取属性

@GetMapping("demo")
 public String demo(@AuthenticationPrincipal(expression = "username") String username) {
   return username;
}

@CurrentSecurityContext

spring security 5.0提供注解,用来获取当前用户的上下文

@GetMapping("/currentusername")
public String currentUserName(@CurrentSecurityContext(expression = "authentication") 
  Authentication authentication) {
        return authentication.getName();
}

expression 支持spel表达式,可以通过authentication.principal获取Principal对象

HttpServletRequest

@GetMapping("demo")
public String demo(HttpServletRequest request) {
        return request.getUserPrincipal().getName();
}