提交 | 用户 | 时间
|
e7c126
|
1 |
package com.iailab.framework.security.core.context; |
H |
2 |
|
|
3 |
import com.alibaba.ttl.TransmittableThreadLocal; |
|
4 |
import org.springframework.security.core.context.SecurityContext; |
|
5 |
import org.springframework.security.core.context.SecurityContextHolderStrategy; |
|
6 |
import org.springframework.security.core.context.SecurityContextImpl; |
|
7 |
import org.springframework.util.Assert; |
|
8 |
|
|
9 |
/** |
|
10 |
* 基于 TransmittableThreadLocal 实现的 Security Context 持有者策略 |
|
11 |
* 目的是,避免 @Async 等异步执行时,原生 ThreadLocal 的丢失问题 |
|
12 |
* |
|
13 |
* @author iailab |
|
14 |
*/ |
|
15 |
public class TransmittableThreadLocalSecurityContextHolderStrategy implements SecurityContextHolderStrategy { |
|
16 |
|
|
17 |
/** |
|
18 |
* 使用 TransmittableThreadLocal 作为上下文 |
|
19 |
*/ |
|
20 |
private static final ThreadLocal<SecurityContext> CONTEXT_HOLDER = new TransmittableThreadLocal<>(); |
|
21 |
|
|
22 |
@Override |
|
23 |
public void clearContext() { |
|
24 |
CONTEXT_HOLDER.remove(); |
|
25 |
} |
|
26 |
|
|
27 |
@Override |
|
28 |
public SecurityContext getContext() { |
|
29 |
SecurityContext ctx = CONTEXT_HOLDER.get(); |
|
30 |
if (ctx == null) { |
|
31 |
ctx = createEmptyContext(); |
|
32 |
CONTEXT_HOLDER.set(ctx); |
|
33 |
} |
|
34 |
return ctx; |
|
35 |
} |
|
36 |
|
|
37 |
@Override |
|
38 |
public void setContext(SecurityContext context) { |
|
39 |
Assert.notNull(context, "Only non-null SecurityContext instances are permitted"); |
|
40 |
CONTEXT_HOLDER.set(context); |
|
41 |
} |
|
42 |
|
|
43 |
@Override |
|
44 |
public SecurityContext createEmptyContext() { |
|
45 |
return new SecurityContextImpl(); |
|
46 |
} |
|
47 |
|
|
48 |
} |