问题背景
最近看到群里面有人提问:我想要在DAO层保存数据时,获取到当前登录用户,但是我又不想去做token换用户信息之内的操作,该怎么办?然后他又理了下自己的需求,得出的结果:怎么在非request环境获取到用户信息?
基于这个问题我思考了下我们项目是怎么做的,我们项目用的是security,在每次需要用户信息的时候调用SecurityContextHolder.getContext()方法获取到SecurityContext对象,再从中拿到Authentication对象,最终拿到用户信息的;问题来了,我们调用getContext()方法时,没有任何入参,他是怎么知道我们当前用户是张三,而不是李四,不会拿错用户信息的呢?
探索过程
看这个问题之前,得先了解security和对应的Authentication等基础知识,不过不了解也没关系,我们最终的目的是分析threalocal这个东西,不了解security也能看懂本文
既然获取用户信息是调用这个方法开始,那我们SecurityContextHolder.getContext()开始入手;
org.springframework.security.core.context.SecurityContextHolder#getContext()
//该方法返回一个SecurityContext 对象
public static SecurityContext getContext() {
//strategy,这个单词很重要,又到了学习知识的时候了,音标 [ˈstrætədʒi],策略的意思,该接口SecurityContextHolderStrategy有三个实现类,我们依次看下
return strategy.getContext();
}
//可以看到SecurityContext 是一个接口,主要包含设置和获取Authentication 对象,Authentication 是security封装用户认证鉴权信息的一个包装类
public interface SecurityContext extends Serializable {
// ~ Methods
// ========================================================================================================
/**
* Obtains the currently authenticated principal, or an authentication request token.
*
* @return the <code>Authentication</code> or <code>null</code> if no authentication
* information is available
*/
Authentication getAuthentication();
/**
* Changes the currently authenticated principal, or removes the authentication
* information.
*
* @param authentication the new <code>Authentication</code> token, or
* <code>null</code> if no further authentication information should be stored
*/
void setAuthentication(Authentication authentication);
}
通过该类的注释可以看到,A strategy for storing security context information against a thread.(针对线程存储安全上下文信息的策略),说明用户信息和线程相关的,我们点开第三个ThreadLocalSecurityContextHolderStrategy看看
org.springframework.security.core.context.ThreadLocalSecurityContextHolderStrategy
//该类的类名注释:A ThreadLocal-based implementation of SecurityContextHolderStrategy.这个太简单了就不翻译了,从这儿可以看出当前用户信息和当前请求线程是绑定到ThreadLocal里面的
final class ThreadLocalSecurityContextHolderStrategy implements
SecurityContextHolderStrategy {
// ~ Static fields/initializers
// =====================================================================================
//正儿八经的ThreadLocal
private static final ThreadLocal<SecurityContext> contextHolder = new ThreadLocal<>();
// ~ Methods
// ========================================================================================================
//移除用户信息
public void clearContext() {
contextHolder.remove();
}
//获取用户信息
public SecurityContext getContext() {
SecurityContext ctx = contextHolder.get();
if (ctx == null) {
ctx = createEmptyContext();
contextHolder.set(ctx);
}
return ctx;
}
//保存用户信息
public void setContext(SecurityContext context) {
Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
contextHolder.set(context);
}
从以上代码可以得出结论,security通过对象的封装将用户认证鉴权信息放到了SecurityContext ,然后再将SecurityContext 存入ThreadLocal中,并将提供一个SecurityContextHolder的静态工具类来获取SecurityContext ;
到此我们就知道了Security是怎么保存用户信息和获取用户信息的
我们顺便看看SecurityContextHolderStrategy 其它两个实现,代码如下
org.springframework.security.core.context.InheritableThreadLocalSecurityContextHolderStrategy
//和ThreadLocalSecurityContextHolderStrategy 一致,也是基于ThreadLocal来实现存储
final class InheritableThreadLocalSecurityContextHolderStrategy implements
SecurityContextHolderStrategy {
// ~ Static fields/initializers
// =====================================================================================
private static final ThreadLocal<SecurityContext> contextHolder = new InheritableThreadLocal<>();
// ~ Methods
// ========================================================================================================
public void clearContext() {
contextHolder.remove();
}
public SecurityContext getContext() {
SecurityContext ctx = contextHolder.get();
if (ctx == null) {
ctx = createEmptyContext();
contextHolder.set(ctx);
}
return ctx;
}
public void setContext(SecurityContext context) {
Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
contextHolder.set(context);
}
org.springframework.security.core.context.GlobalSecurityContextHolderStrategy
//该策略的实现用的是一个静态SecurityContext 存储,没用ThreadLocal,在多线程环境下会发生安全问题,导致值被覆盖,通过该类的注释也可以看出[This means that all instances in the JVM share the same SecurityContext. This is generally useful with rich clients, such as Swing.] (这意味着JVM中的所有实例共享相同的SecurityContext。这对于Swing这样的富客户端通常很有用。)
final class GlobalSecurityContextHolderStrategy implements SecurityContextHolderStrategy {
// ~ Static fields/initializers
// =====================================================================================
private static SecurityContext contextHolder;
// ~ Methods
// ========================================================================================================
public void clearContext() {
contextHolder = null;
}
public SecurityContext getContext() {
if (contextHolder == null) {
contextHolder = new SecurityContextImpl();
}
return contextHolder;
}
public void setContext(SecurityContext context) {
Assert.notNull(context, "Only non-null SecurityContext instances are permitted");
contextHolder = context;
}
到此本文就完成了一半了,接下来我们可以再看看ThreadLocal,他到底是怎么玩的,看结构和是个map,看看他和我们熟知的hashMap有啥不一样:从获取当前用户到Security再到ThreadLocal(二)