当前位置: 首页 > news >正文

spring security reactive获取security context

本文主要研究下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>} to set in the returned
	 * Reactor {@link Context}
	 * @return a Reactor {@link Context} that contains the {@code Mono<SecurityContext>}
	 */
	public static Context withSecurityContext(Mono<? extends SecurityContext> securityContext) {
		return Context.of(SECURITY_CONTEXT_KEY, securityContext);
	}

	/**
	 * A shortcut for {@link #withSecurityContext(Mono)}
	 * @param authentication the {@link Authentication} to be used
	 * @return a Reactor {@link Context} that contains the {@code Mono<SecurityContext>}
	 */
	public static Context withAuthentication(Authentication authentication) {
		return withSecurityContext(Mono.just(new SecurityContextImpl(authentication)));
	}
}
复制代码

可以看到,这里利用了reactor提供的context机制来进行异步线程的变量传递。

实例

    public Mono<User> getCurrentUser() {
        return ReactiveSecurityContextHolder.getContext()
                .switchIfEmpty(Mono.error(new IllegalStateException("ReactiveSecurityContext is empty")))
                .map(SecurityContext::getAuthentication)
                .map(Authentication::getPrincipal)
                .cast(User.class);
    }
复制代码

源码解析

ServerHttpSecurity

spring-security-config-5.0.3.RELEASE-sources.jar!/org/springframework/security/config/web/server/ServerHttpSecurity.java

	public SecurityWebFilterChain build() {
		if(this.built != null) {
			throw new IllegalStateException("This has already been built with the following stacktrace. " + buildToString());
		}
		this.built = new RuntimeException("First Build Invocation").fillInStackTrace();
		if(this.headers != null) {
			this.headers.configure(this);
		}
		WebFilter securityContextRepositoryWebFilter = securityContextRepositoryWebFilter();
		if(securityContextRepositoryWebFilter != null) {
			this.webFilters.add(securityContextRepositoryWebFilter);
		}
		if(this.csrf != null) {
			this.csrf.configure(this);
		}
		if(this.httpBasic != null) {
			this.httpBasic.authenticationManager(this.authenticationManager);
			this.httpBasic.configure(this);
		}
		if(this.formLogin != null) {
			this.formLogin.authenticationManager(this.authenticationManager);
			if(this.securityContextRepository != null) {
				this.formLogin.securityContextRepository(this.securityContextRepository);
			}
			if(this.formLogin.authenticationEntryPoint == null) {
				this.webFilters.add(new OrderedWebFilter(new LoginPageGeneratingWebFilter(), SecurityWebFiltersOrder.LOGIN_PAGE_GENERATING.getOrder()));
				this.webFilters.add(new OrderedWebFilter(new LogoutPageGeneratingWebFilter(), SecurityWebFiltersOrder.LOGOUT_PAGE_GENERATING.getOrder()));
			}
			this.formLogin.configure(this);
		}
		if(this.logout != null) {
			this.logout.configure(this);
		}
		this.requestCache.configure(this);
		this.addFilterAt(new SecurityContextServerWebExchangeWebFilter(), SecurityWebFiltersOrder.SECURITY_CONTEXT_SERVER_WEB_EXCHANGE);
		if(this.authorizeExchange != null) {
			ServerAuthenticationEntryPoint authenticationEntryPoint = getAuthenticationEntryPoint();
			ExceptionTranslationWebFilter exceptionTranslationWebFilter = new ExceptionTranslationWebFilter();
			if(authenticationEntryPoint != null) {
				exceptionTranslationWebFilter.setAuthenticationEntryPoint(
					authenticationEntryPoint);
			}
			this.addFilterAt(exceptionTranslationWebFilter, SecurityWebFiltersOrder.EXCEPTION_TRANSLATION);
			this.authorizeExchange.configure(this);
		}
		AnnotationAwareOrderComparator.sort(this.webFilters);
		List<WebFilter> sortedWebFilters = new ArrayList<>();
		this.webFilters.forEach( f -> {
			if(f instanceof OrderedWebFilter) {
				f = ((OrderedWebFilter) f).webFilter;
			}
			sortedWebFilters.add(f);
		});
		return new MatcherSecurityWebFilterChain(getSecurityMatcher(), sortedWebFilters);
	}
复制代码

这里的build方法创建了securityContextRepositoryWebFilter并添加到webFilters里头

securityContextRepositoryWebFilter

	private WebFilter securityContextRepositoryWebFilter() {
		ServerSecurityContextRepository repository = this.securityContextRepository;
		if(repository == null) {
			return null;
		}
		WebFilter result = new ReactorContextWebFilter(repository);
		return new OrderedWebFilter(result, SecurityWebFiltersOrder.REACTOR_CONTEXT.getOrder());
	}
复制代码

这里创建了ReactorContextWebFilter

ReactorContextWebFilter

spring-security-web-5.0.3.RELEASE-sources.jar!/org/springframework/security/web/server/context/ReactorContextWebFilter.java

public class ReactorContextWebFilter implements WebFilter {
	private final ServerSecurityContextRepository repository;

	public ReactorContextWebFilter(ServerSecurityContextRepository repository) {
		Assert.notNull(repository, "repository cannot be null");
		this.repository = repository;
	}

	@Override
	public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
		return chain.filter(exchange)
			.subscriberContext(c -> c.hasKey(SecurityContext.class) ? c :
				withSecurityContext(c, exchange)
			);
	}

	private Context withSecurityContext(Context mainContext, ServerWebExchange exchange) {
		return mainContext.putAll(this.repository.load(exchange)
			.as(ReactiveSecurityContextHolder::withSecurityContext));
	}
}
复制代码

这里使用reactor的subscriberContext将SecurityContext注入进去。

小结

基于reactor提供的context机制,spring security也相应提供了ReactiveSecurityContextHolder用来获取当前用户,非常便利。

doc

  • 聊聊reactor异步线程的变量传递
  • 5.10.3 EnableReactiveMethodSecurity

相关文章:

  • rocketMq概念介绍
  • PHP垃圾回收机制
  • SpringCloud |第三篇: 服务消费者(Feign+REST)
  • Android请求网络数据下载APK安装包
  • 这几个编码小技巧将令你 PHP 代码更加简洁
  • 技术相对论之软件架构
  • Fragment 生命周期怎么来的?
  • Redis和Memcache和MongoDB简介及区别分析(整理)
  • ubuntu16.4安装最新版wine3.0
  • c++中局部变量初始化的问题
  • WordCount
  • 外卖也智能!美团骑手智能助手的技术与实践
  • 【协议转换和消息路由】camel-spring-boot-starter 实践
  • 坑货!阿里奇门中心
  • [ssh]如何设计ARM板上多用户key登录系统
  • ➹使用webpack配置多页面应用(MPA)
  • Cumulo 的 ClojureScript 模块已经成型
  • Debian下无root权限使用Python访问Oracle
  • Docker 1.12实践:Docker Service、Stack与分布式应用捆绑包
  • Javascript设计模式学习之Observer(观察者)模式
  • Redis字符串类型内部编码剖析
  • uva 10370 Above Average
  • Yii源码解读-服务定位器(Service Locator)
  • 成为一名优秀的Developer的书单
  • 短视频宝贝=慢?阿里巴巴工程师这样秒开短视频
  • 用 vue 组件自定义 v-model, 实现一个 Tab 组件。
  • 在Docker Swarm上部署Apache Storm:第1部分
  • NLPIR智能语义技术让大数据挖掘更简单
  • 阿里云ACE认证之理解CDN技术
  • ​【原创】基于SSM的酒店预约管理系统(酒店管理系统毕业设计)
  • ​云纳万物 · 数皆有言|2021 七牛云战略发布会启幕,邀您赴约
  • ​总结MySQL 的一些知识点:MySQL 选择数据库​
  • #!/usr/bin/python与#!/usr/bin/env python的区别
  • (12)Hive调优——count distinct去重优化
  • (MonoGame从入门到放弃-1) MonoGame环境搭建
  • (二)什么是Vite——Vite 和 Webpack 区别(冷启动)
  • (力扣)1314.矩阵区域和
  • (全注解开发)学习Spring-MVC的第三天
  • (转)Linux下编译安装log4cxx
  • .NET MVC、 WebAPI、 WebService【ws】、NVVM、WCF、Remoting
  • .net on S60 ---- Net60 1.1发布 支持VS2008以及新的特性
  • .Net Winform开发笔记(一)
  • .NET 同步与异步 之 原子操作和自旋锁(Interlocked、SpinLock)(九)
  • .NET/C# 将一个命令行参数字符串转换为命令行参数数组 args
  • .net解析传过来的xml_DOM4J解析XML文件
  • .net与java建立WebService再互相调用
  • .net中应用SQL缓存(实例使用)
  • /etc/skel 目录作用
  • :如何用SQL脚本保存存储过程返回的结果集
  • @Autowired自动装配
  • @Mapper作用
  • @property @synthesize @dynamic 及相关属性作用探究
  • @selector(..)警告提示
  • [2023年]-hadoop面试真题(一)
  • [acwing周赛复盘] 第 94 场周赛20230311