我需要编写一个会话bean,代码中的某个位置检查当前用户是否有某些角色。
要对我的EJB3进行单元测试,我正在尝试OpenEJB。我按照他们关于testing security的例子,但如果我在代码中测试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();
}
}
}
答案 0 :(得分:0)
@RunAs
不会改变委托人的权限。
我在OpenEJB论坛上发布了相同的问题(见Nabble)并获得了更多信息以及更好的解决方案。