[英]Getting the current logged in user name when using Spring Security
Its a coupon system app using Spring security, spring MVC, now. 它是一个使用Spring Security Spring MVC的优惠券系统应用程序。 when the app starts, I need to somehow initialize the current logged in user into the controller.
当应用启动时,我需要以某种方式将当前登录的用户初始化到控制器中。
Issue is: 问题是:
Is there anything I'm missing? 有什么我想念的吗? a different approach of getting the current logged in user after he logs in?
在登录后获得当前登录用户的另一种方法?
What you need is called @AuthenticationPrincipal
. 您需要的是
@AuthenticationPrincipal
。 You can inject it in controller method like this: 您可以将其注入控制器方法中,如下所示:
@GetMapping("/")
public void get(@AuthinticationPrincipal User user){ ... }
Here is documentation 这是文档
Alternatively, you can create your own annotation and custom argument resolver, and inject whatever you want. 或者,您可以创建自己的注释和自定义参数解析器,然后注入所需的任何内容。
Solution 1: Principal principal 解决方案1:校长
@RequestMapping(value = {"/", ""})
public String start(Principal principal, Model model) {
String currentUser = principal.getName();
return currentUser;
}
Solution 2: Authentication authentication 解决方案2:身份验证
@RequestMapping(value = {"/", ""})
public String currentUserName(Authentication authentication) {
return authentication.getName();
}
Solution 3: SecurityContextHolder 解决方案3:SecurityContextHolder
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
String username = ((UserDetails)principal).getUsername();
} else {
String username = principal.toString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.