对于最新的稳定版本,请使用 Spring Security 6.5.3! |
运行身份身份验证替换
概述
这AbstractSecurityInterceptor
能够临时替换Authentication
对象SecurityContext
和SecurityContextHolder
在安全对象回调阶段。仅当原始Authentication
对象已成功处理AuthenticationManager
和AccessDecisionManager
.
这RunAsManager
将指示更换Authentication
对象(如果有),则应在SecurityInterceptorCallback
.
通过临时将Authentication
对象,则安全调用将能够调用需要不同身份验证和授权凭据的其他对象。它还能够对特定GrantedAuthority
对象。 因为 Spring Security 提供了许多帮助程序类,这些类可以根据SecurityContextHolder
,这些运行方式替换在调用远程 Web 服务时特别有用。
配置
一个RunAsManager
接口由 Spring Security 提供:
Authentication buildRunAs(Authentication authentication, Object object,
List<ConfigAttribute> config);
boolean supports(ConfigAttribute attribute);
boolean supports(Class clazz);
第一个方法返回Authentication
对象,该对象应替换现有的Authentication
对象。如果方法返回null
,则表示不应进行替换。第二种方法由AbstractSecurityInterceptor
作为其配置属性启动验证的一部分。 这supports(Class)
方法被安全拦截器实现调用,以确保配置的RunAsManager
支持安全拦截器将呈现的安全对象类型。
一个具体的实现RunAsManager
随 Spring Security 一起提供。 这RunAsManagerImpl
类返回替换RunAsUserToken
如果有ConfigAttribute
开头为RUN_AS_
. 如果有此类ConfigAttribute
找到,替换RunAsUserToken
将包含与原始相同的主体、凭据和授予的权限Authentication
对象,以及新的SimpleGrantedAuthority
对于每个RUN_AS_
ConfigAttribute
. 每个新的SimpleGrantedAuthority
前缀为ROLE_
,后跟RUN_AS
ConfigAttribute
. 例如,一个RUN_AS_SERVER
将导致替换RunAsUserToken
包含一个ROLE_RUN_AS_SERVER
授予权力。
替换RunAsUserToken
就像其他的一样Authentication
对象。 它需要通过AuthenticationManager
,可能通过委托给合适的AuthenticationProvider
.
这RunAsImplAuthenticationProvider
执行此类身份验证。它只是接受任何有效的RunAsUserToken
提出。
确保恶意代码不会创建RunAsUserToken
并出示它以保证被RunAsImplAuthenticationProvider
,密钥的哈希值存储在所有生成的Tokens中。 这RunAsManagerImpl
和RunAsImplAuthenticationProvider
在 bean 上下文中使用相同的键创建:
<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
可以验证它是由已批准的RunAsManagerImpl
.
这RunAsUserToken
出于安全原因,创建后不可变