序
本文主要研究下reactive模式下的spring security context的获取。
ReactiveSecurityContextHolder
springboot2支持了webflux的异步模式,那么传统的基于threadlocal的SecurityContextHolder就不管用了。spring security5.x也支持了reactive方式,这里就需要使用reactive版本的SecurityContextHolder
spring-security-core-5.0.3.RELEASE-sources.jar!/org/springframework/security/core/context/ReactiveSecurityContextHolder.java
public class ReactiveSecurityContextHolder {
private static final Class<?> SECURITY_CONTEXT_KEY = SecurityContext.class;
/**
* Gets the {@code Mono<SecurityContext>} from Reactor {@link Context}
* @return the {@code Mono<SecurityContext>}
*/
public static Mono<SecurityContext> getContext() {
return Mono.subscriberContext()
.filter( c -> c.hasKey(SECURITY_CONTEXT_KEY))
.flatMap( c-> c.<Mono<SecurityContext>>get(SECURITY_CONTEXT_KEY));
}
/**
* Clears the {@code Mono<SecurityContext>} from Reactor {@link Context}
* @return Return a {@code Mono<Void>} which only replays complete and error signals
* from clearing the context.
*/
public static Function<Context, Context> clearContext() {
return context -> context.delete(SECURITY_CONTEXT_KEY);
}
/**
* Creates a Reactor {@link Context} that contains the {@code Mono<SecurityContext>}
* that can be merged into another {@link Context}
* @param securityContext the {@code Mono<SecurityContext&