1

我需要编写一个会话 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();
        }

    }
}
4

1 回答 1

0

好吧,显然它不应该工作。它是规范的一部分,@RunAs不会更改委托人的权限。

我在 OpenEJB 论坛上发布了相同的问题(在Nabble上查看)并在那里获得了更多信息以及更好的解决方案。

于 2011-02-11T08:44:48.270 回答