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
版权声明:本文为博主原创文章,转载请附上博文链接!
转载于:https://www.cnblogs.com/YLLLike/p/10746627.html