我需要编写一个会话bean,在代码中的某个位置检查当前用户是否具有某种角色。
为了统一我的EJB3,我正在试用OpenEJB。我学习了他们关于测试安全性的例子,但是如果我用SessionContect.isCallerInRole()在代码中测试角色,它总是返回false。
为什么不起作用?
我写了一些代码来说明。
我的本地界面:
@Local
public interface MyBean {
boolean doSomething();
}我的EJB:
@Stateless
public class MyBeanImpl implements MyBean {
@Resource
private SessionContext sessionContext;
@Override
public boolean doSomething() {
return this.sessionContext.isCallerInRole("role1");
}
}我的测试:
public class MyBeanTest {
private Context context;
@Before
public void setUp() throws Exception {
final Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.client.LocalInitialContextFactory");
this.context = new InitialContext(properties);
}
@Test
public void test1() throws Exception {
final Caller roleBean = (Caller) this.context.lookup("RoleBeanLocal");
roleBean.call(new Callable<Object>() {
@Override
public Object call() throws Exception {
final MyBean myBean = (MyBean) MyBeanTest.this.context.lookup("MyBeanImplLocal");
Assert.assertTrue(myBean.doSomething());
return null;
}
});
}
@Test
public void test2() throws Exception {
final Caller role2Bean = (Caller) this.context.lookup("Role2BeanLocal");
role2Bean.call(new Callable<Object>() {
@Override
public Object call() throws Exception {
final MyBean myBean = (MyBean) MyBeanTest.this.context.lookup("MyBeanImplLocal");
Assert.assertFalse(myBean.doSomething());
return null;
}
});
}
public static interface Caller {
<V> V call(Callable<V> callable) throws Exception;
}
@Stateless
@RunAs("role1")
public static class RoleBean implements Caller {
@Override
public <V> V call(final Callable<V> callable) throws Exception {
return callable.call();
}
}
@Stateless
@RunAs("role2")
public static class Role2Bean implements Caller {
@Override
public <V> V call(final Callable<V> callable) throws Exception {
return callable.call();
}
}
}发布于 2011-02-11 08:44:48
很显然这不应该起作用。@RunAs不更改主体的权限是规范的一部分。
我在OpenEJB论坛上发布了同样的问题(见纳布尔),并获得了更多的信息以及更好的解决方案。
https://stackoverflow.com/questions/4877159
复制相似问题