目前,我正在使用spring安全和@PreAuthorize注释来保护方法调用。现在,我想要更改方法调用的身份验证令牌,就像spring security的run-as authentication replacement所允许的那样。
我可以在每个方法的基础上配置替换吗?每个注释,SpEL表达式....如果不是,是否有可能在runAsManager中计算出调用的是什么方法?我到底该如何配置安全对象的安全配置属性呢?
发布于 2012-08-24 15:03:17
我通过实现自己的RunAsManager解决了这个问题,它检查被调用方法上的自定义注释并返回适当的令牌。
效果很好。
发布于 2014-07-06 01:33:17
我已经发布了结合@PreAuthorize实现Run-As的a detailed article。
1)实现您自己的RunAsManager,它基于任何自定义逻辑创建在方法执行过程中使用的Authentication。下面的示例使用了一个自定义注释,它提供了额外的角色:
public class AnnotationDrivenRunAsManager extends RunAsManagerImpl {
@Override
public Authentication buildRunAs(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
if(!(object instanceof ReflectiveMethodInvocation) || ((ReflectiveMethodInvocation)object).getMethod().getAnnotation(RunAsRole.class) == null) {
return super.buildRunAs(authentication, object, attributes);
}
String roleName = ((ReflectiveMethodInvocation)object).getMethod().getAnnotation(RunAsRole.class).value();
if (roleName == null || roleName.isEmpty()) {
return null;
}
GrantedAuthority runAsAuthority = new SimpleGrantedAuthority(roleName);
List<GrantedAuthority> newAuthorities = new ArrayList<GrantedAuthority>();
// Add existing authorities
newAuthorities.addAll(authentication.getAuthorities());
// Add the new run-as authority
newAuthorities.add(runAsAuthority);
return new RunAsUserToken(getKey(), authentication.getPrincipal(), authentication.getCredentials(),
newAuthorities, authentication.getClass());
}
}此实现将在受保护的方法(例如@RunAsRole("ROLE_AUDITOR"))上查找自定义@RunAsRole注释,如果找到,则会将给定的授权(本例中为ROLE_AUDITOR)添加到授权列表中。RunAsRole本身只是一个简单的自定义注释。
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface RunAsRole {
String value();
}2)实例化管理器:
<bean id="runAsManager"
class="org.springframework.security.access.intercept.RunAsManagerImpl">
<property name="key" value="my_run_as_key"/>
</bean>3)注册:
<global-method-security pre-post-annotations="enabled" run-as-manager-ref="runAsManager">
<expression-handler ref="expressionHandler"/>
</global-method-security>4)控制器中的示例用法:
@Controller
public class TransactionLogController {
@PreAuthorize("hasRole('ROLE_REGISTERED_USER')") //Authority needed to access the method
@RunAsRole("ROLE_AUDITOR") //Authority added by RunAsManager
@RequestMapping(value = "/transactions", method = RequestMethod.GET) //Spring MVC configuration. Not related to security
@ResponseBody //Spring MVC configuration. Not related to security
public List<Transaction> getTransactionLog(...) {
... //Invoke something in the backend requiring ROLE_AUDITOR
{
... //User does not have ROLE_AUDITOR here
}编辑:在RunAsManagerImpl中key的值可以是您想要的任何值。以下是Spring docs中有关其使用的摘录:
为确保恶意代码不会创建
RunAsUserToken并将其提供给RunAsImplAuthenticationProvider保证接受,密钥的散列存储在所有生成的令牌中。RunAsManagerImpl和RunAsImplAuthenticationProvider是使用相同的键在bean上下文中创建的:
https://stackoverflow.com/questions/11667086
复制相似问题