我使用的是spring-security-tiger-2.0.5。
有没有办法以编程方式将安全代理添加到Spring Bean?
我是通过BeanDefinitionBuilder构建bean的,我想添加与@Secured注释相同的行为。
roleName的@Secured等效项将作为参数传递。
答案 0 :(得分:1)
要以编程方式将Spring Security功能注入现有bean,您可能需要使用Spring Security应用程序上下文并在那里注册您的bean:
@Test
public void testSpringSecurity() throws Exception {
InMemoryXmlApplicationContext ctx = initSpringAndSpringSecurity();
// Creates new instance
IMyService secured = (IMyService) ctx.getAutowireCapableBeanFactory()
.initializeBean(new MyService(), "myService");
assertTrue(AopUtils.isAopProxy(secured));
fakeSecurityContext("ROLE_USER");
secured.getCustomers(); // Works: @Secured("ROLE_USER")
fakeSecurityContext("ROLE_FOO");
try {
secured.getCustomers(); // Throws AccessDenied Exception
fail("AccessDeniedException expected");
} catch (AccessDeniedException expected) {
}
}
private InMemoryXmlApplicationContext initSpringAndSpringSecurity() {
InMemoryXmlApplicationContext ctx = new InMemoryXmlApplicationContext(
"<b:bean id='authenticationManager' class='org.springframework.security.MockAuthenticationManager' /> "
+ "<b:bean id='accessDecisionManager' class='org.springframework.security.vote.UnanimousBased'><b:property name='decisionVoters'><b:list><b:bean class='org.springframework.security.vote.RoleVoter'/></b:list></b:property></b:bean>"
+ "<b:bean id='objectDefinitionSource' class='org.springframework.security.annotation.SecuredMethodDefinitionSource' /> "
+ "<b:bean id='autoproxy' class='org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator'/>"
+ "<b:bean id='methodSecurityAdvisor' class='org.springframework.security.intercept.method.aopalliance.MethodDefinitionSourceAdvisor' autowire='constructor'/>"
+ "<b:bean id='securityInterceptor' class='org.springframework.security.intercept.method.aopalliance.MethodSecurityInterceptor'><b:property name='authenticationManager' ref='authenticationManager' /><b:property name='accessDecisionManager' ref='accessDecisionManager' /><b:property name='objectDefinitionSource' ref='objectDefinitionSource' /></b:bean>");
return ctx;
}
我使用了内存中的应用程序上下文,因为其文档中的MethodDefinitionSourceAdvisor
表示自动代理只对ApplicationContext
启用。因此,如果您不为每个服务对象使用单独的ProxyFactoryBean
,我相信您需要自动代理的应用程序上下文。但是,由于您使用的是@Secured
注释,我怀疑这与自动代理相同。
fakeSecurityContext()
只是将具有给定角色的Authentication
对象设置到SecurityContextHolder
中以进行测试。
您可以自行使用Spring Core功能。假设您有一个返回客户列表的服务,并且当前用户只能查看具有特定收入限制的客户。以下测试用例将是我们的开始:
@Test
public void testSecurity() throws Exception {
ClassPathXmlApplicationContext appCtx = new ClassPathXmlApplicationContext(
"spring.xml");
IMyService service = (IMyService) appCtx.getBean("secured",
IMyService.class);
assertEquals(1, service.getCustomers().size());
}
这是原始服务实施:
public class MyService implements IMyService {
public List<Customer> getCustomers() {
return Arrays.asList(new Customer(100000), new Customer(5000));
}
}
在spring.xml
中配置服务对象并添加方法拦截器:
<bean id="service" class="de.mhaller.spring.MyService"></bean>
<bean id="securityInterceptor" class="de.mhaller.spring.MyServiceInterceptor">
<property name="revenueLimit" value="50000"/>
</bean>
<bean id="secured" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="targetName" value="service" />
<property name="interceptorNames">
<list>
<value>securityInterceptor</value>
</list>
</property>
</bean>
安全拦截器实现:
public class MyServiceInterceptor implements MethodInterceptor {
private int revenueLimit = 10000;
public void setRevenueLimit(int revenueLimit) {
this.revenueLimit = revenueLimit;
}
@SuppressWarnings("unchecked")
public Object invoke(MethodInvocation mi) throws Throwable {
List<Customer> filtered = new ArrayList<Customer>();
List<Customer> result = (List<Customer>) mi.proceed();
for (Customer customer : result) {
if (customer.isRevenueBelow(revenueLimit)) {
filtered.add(customer);
}
}
return filtered;
}
}
使用这种方法的好处是,您不仅可以声明性地检查当前用户的角色,还可以动态地强制执行公司策略,例如:根据业务值限制返回的对象。
答案 1 :(得分:1)
感谢答案,但我最终以完全编程的方式使用它。这不是一个简单的解决方案,但我想分享它。
首先,我可以将问题分成两部分:
1)为我自己的bean创建代理。
2)将安全角色添加到每个bean。不幸的是,我无法添加基于xml的切入点,因为bean都是相同的类(通用服务)。我想要一种方法以不同的方式保护每个bean,尽管它们都是同一个类。 我决定使用aopalliance使用的相同声明((执行。等...)
对于他可能感兴趣的人,我就是这样做的:
1)使用spring的BeanNameAutoProxyCreator类,用于创建我手动添加的类的代理:
private void addProxies(ConfigurableListableBeanFactory beanFactory, List<String> exportedServices) {
List<String> interceptorNames = findInterceptorNames(beanFactory);
BeanNameAutoProxyCreator beanPostProcessor = new BeanNameAutoProxyCreator();
beanPostProcessor.setBeanNames(exportedServices.toArray(new String[exportedServices.size()]));
beanPostProcessor.setInterceptorNames(interceptorNames.toArray(new String[interceptorNames.size()]));
beanPostProcessor.setBeanFactory(beanFactory);
beanPostProcessor.setOrder(Ordered.LOWEST_PRECEDENCE);
beanFactory.addBeanPostProcessor(beanPostProcessor);
}
@SuppressWarnings("unchecked")
private List<String> findInterceptorNames(ConfigurableListableBeanFactory beanFactory) {
List<String> interceptorNames = new ArrayList<String>();
List<? extends Advisor> list = new BeanFactoryAdvisorRetrievalHelper(beanFactory).findAdvisorBeans();
for (Advisor ad : list) {
Advice advice = ad.getAdvice();
if (advice instanceof MethodInterceptor) {
Map<String, ?> beansOfType = beanFactory.getBeansOfType(advice.getClass());
for (String name : beansOfType.keySet()) {
interceptorNames.add(name);
}
}
}
return interceptorNames;
}
2)对于可参数化的类似安全的部分:
创建了spring的MethodDefinitionSource的实现。 MethodSecurityProxy使用此接口的实现来在运行时获取securedObjects。
@SuppressWarnings("unchecked")
@Override
public ConfigAttributeDefinition getAttributes(Object object) throws IllegalArgumentException {
if (!(object instanceof ReflectiveMethodInvocation)) {
return null;
}
ReflectiveMethodInvocation invokation = (ReflectiveMethodInvocation) object;
if (!(invokation.getThis() instanceof MyService)) {
return null;
}
MyService service = (MyService) invokation.getThis();
Map<String, String> map =getProtectedServiceMethodMap(service);
String roles = map.get(MethodKeyGenerator.generate(invokation.getMethod()));
return roles == null ? null : new ConfigAttributeDefinition(StringUtils.delimitedListToStringArray(roles, ","));
}
最棘手的部分是将我的MethodDefinitionSource impl注册到applicationContext中,以便MethodSecurityInterceptor了解它:
private void addCrudDefinitionSource() {
DelegatingMethodDefinitionSource source = (DelegatingMethodDefinitionSource) beanFactory.getBean(BeanIds.DELEGATING_METHOD_DEFINITION_SOURCE);
try {
Field field = source.getClass().getDeclaredField("methodDefinitionSources");
field.setAccessible(true);
List list = (List) field.get(source);
list.add(new MyMethodDefinitionSource());
} catch (Exception e) {
e.printStackTrace();
}
}
最后,为了检查aop风格的方法入口点,我使用了如下代码:
private void addToCache(){ // Ommiting parameters
PointcutExpression expression = parser.parsePointcutExpression(fullExpression);
Method[] methods = clazzToCheck.getMethods();
for (int i = 0; i < methods.length; i++) {
Method currentMethod = methods[i];
boolean matches = expression.matchesMethodExecution(currentMethod).alwaysMatches();
if (matches){
//Add to Cache
}
}
答案 2 :(得分:0)
你应该看看org.springframework.aop.framework.ProxyFactory 类。用ProxyFactory包装你的bean并添加安全拦截器