Spring Boot

Spring框架借助ThreadLocal来保存和传递用户登录信息。我们通常是使用下面这段代码,来获取保存在ThreadLocal中的用户信息。

SecurityContextHolder.getContext().getAuthentication().getPrincipal();


如果我们想获取用户的ID,可以这样:

String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().getUserId();


一,我们来看一下源代码


public class SecurityContextHolder extends Object,这个类直接继承自Object
官方文档说明如下:
Associates a given SecurityContext with the current execution thread.
    这句话大概的意思是,SecurityContextHolder的主要功能是将当前正在执行的thread与SecurityContext关联起来。


进一步详细的说明是:
This class provides a series of static methods that delegate to an instance of
SecurityContextHolderStrategy. The purpose of the class is to provide a convenient way to specify the strategy
that should be used for a given JVM. This is a JVM-wide setting, since everything in this class is static to facilitate

ease of use in calling code.


To specify which strategy should be used, you must provide a mode setting. A mode setting is one of the three valid
MODE_ settings defined as static final fields, or a fully qualified classname to a concrete implementation of
SecurityContextHolderStrategy that provides a public no-argument constructor.


There are two ways to specify the desired strategy mode String. The first is to specify it via the system property
keyed on SYSTEM_PROPERTY. The second is to call setStrategyName(String) before using the class. If neither approach is used,
 the class will default to using MODE_THREADLOCAL, which is backwards compatible, has fewer JVM incompatibilities and is
appropriate on servers (whereas MODE_GLOBAL is definitely inappropriate for server use).


SecurityContextHolder 类提供了8个成员方法,大部分都是static类型:
static SecurityContext getContext() 通过这个方法获得当前的SecurityContext


SecurityContextHolder 类提供了8个成员方法,大部分都是static类型:
static SecurityContext getContext() 通过这个方法获得当前的SecurityContext


然后,调用public interface SecurityContext extends Serializable,这个接口的  Authentication getAuthentication() 方法,
最后,调用public interface Authentication extends Principal, Serializable 接口的 Object getPrincipal() 方法,这个方法的官方说明
是:The identity of the principal being authenticated.


二,Spring的权限机制

流程:

1,用户登录;

2,根据用户ID,获取当前用户所拥有的所有权限;

3,把权限放到session中;

4,显示用户所拥有的资源。


下面我们来说一下详细的实现细节:
---------------------
作者:春秋战国程序猿
来源:CSDN
原文:https://blog.csdn.net/reggergdsg/article/details/50774714
版权声明:本文为博主原创文章,转载请附上博文链接!

posted on 2019-04-21 20:06  YLLike 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/YLLLike/p/10746627.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值