spring security之获取当前用户信息

1 通过 SecurityContextHolder 获取

SecurityContextHolder内部存储了当前与应用程序交互的主体的详细信息。 Spring Security 使用Authentication对象来表示此信息。 通常不需要自己创建Authentication对象,但是由于经常需要查询Authentication对象是相当普遍的。 可以在应用程序中的任何位置使用以下代码块来获取当前经过身份验证的用户的名称,例如:

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if (principal instanceof UserDetails) {
    String username = ((UserDetails)principal).getUsername();
} else {
    String username = principal.toString();
}

调用getContext()返回的对象是SecurityContext接口的一个实例。 这是保存在线程本地存储中的对象。 Spring Security 中的大多数身份验证机制都将UserDetails实例返回为主体。

2 通过 Authentication 获取

public Object getCurrentUser(Authentication authentication){
      return authentication;
}

3 通过@AuthenticationPrincipal 获取

public Object getCurrentUser(@AuthenticationPrincipal UserDetails user){
     return user;
}

4 通过 Principal 获取

public Object getCurrentUser(Principal principal){
      return authentication;
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值