此版本仍在开发中,尚未被视为稳定版本。对于最新的稳定版本,请使用 Spring Security 6.4.3spring-doc.cadn.net.cn

运行方式身份验证替换

概述

AbstractSecurityInterceptor能够临时替换Authentication对象在SecurityContextSecurityContextHolder在 Secure Object 回调阶段。 仅当原始Authentication对象已成功由AuthenticationManagerAccessDecisionManager. 这RunAsManager将指示替换Authentication对象(如果有)中,应在SecurityInterceptorCallback.spring-doc.cadn.net.cn

通过临时替换Authentication对象,则安全调用将能够调用需要不同身份验证和授权凭据的其他对象。 它还将能够对特定的GrantedAuthority对象。 由于 Spring Security 提供了许多帮助程序类,这些类会根据SecurityContextHolder,这些 run-as 替换在调用远程 Web 服务时特别有用。spring-doc.cadn.net.cn

配置

一个RunAsManager接口由 Spring Security 提供:spring-doc.cadn.net.cn

Authentication buildRunAs(Authentication authentication, Object object,
	List<ConfigAttribute> config);

boolean supports(ConfigAttribute attribute);

boolean supports(Class clazz);

第一个方法返回Authentication对象,该对象应替换现有的Authenticationobject 来指定方法调用的持续时间。 如果该方法返回null,则表示不应进行替换。 第二种方法由AbstractSecurityInterceptor作为其配置属性启动验证的一部分。 这supports(Class)方法,以确保配置的RunAsManager支持安全侦听器将呈现的安全对象的类型。spring-doc.cadn.net.cn

一个RunAsManager随 Spring Security 一起提供。 这RunAsManagerImplclass 返回一个替换RunAsUserToken如果有ConfigAttribute开头为RUN_AS_. 如果有ConfigAttribute,则替换RunAsUserToken将包含与原始Authenticationobject 以及新的SimpleGrantedAuthority对于每个RUN_AS_ ConfigAttribute. 每个新的SimpleGrantedAuthority将以ROLE_,后跟RUN_AS ConfigAttribute. 例如,RUN_AS_SERVER将导致替换RunAsUserToken包含一个ROLE_RUN_AS_SERVER授予权限。spring-doc.cadn.net.cn

替代品RunAsUserToken就像任何其他Authentication对象。 它需要由AuthenticationManager,可能通过委托给合适的AuthenticationProvider. 这RunAsImplAuthenticationProvider执行此类身份验证。 它只是接受任何RunAsUserToken提出。spring-doc.cadn.net.cn

为确保恶意代码不会创建RunAsUserToken并出示它以保证被RunAsImplAuthenticationProvider,则密钥的哈希值将存储在所有生成的令牌中。 这RunAsManagerImplRunAsImplAuthenticationProvider在 bean 上下文中使用相同的键创建:spring-doc.cadn.net.cn

<bean id="runAsManager"
	class="org.springframework.security.access.intercept.RunAsManagerImpl">
<property name="key" value="my_run_as_password"/>
</bean>

<bean id="runAsAuthenticationProvider"
	class="org.springframework.security.access.intercept.RunAsImplAuthenticationProvider">
<property name="key" value="my_run_as_password"/>
</bean>

通过使用相同的密钥,每个RunAsUserToken可以验证它是由 Approved 创建的RunAsManagerImpl. 这RunAsUserToken出于安全原因,在创建后是不可变的spring-doc.cadn.net.cn