【问题标题】:OpenEJB & JUnit: Sessioncontext.isCallerInRole returns allways falseOpenEJB 和 JUnit:Sessioncontext.isCallerInRole 总是返回 false
【发布时间】:2011-02-02 16:41:50
【问题描述】:

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

    }
}

【问题讨论】:

    标签: java junit ejb-3.0 openejb


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2021-11-05
      • 2018-11-05
      • 2019-05-06
      • 2017-04-29
      相关资源
      最近更新 更多