OpenEJB & JUnit: Sessioncontext.isCallerInRole returns allways false

1.2k views Asked by At

I need to write a session bean that somewhere in the code checks if the current user has some role(s).

To unittest my EJB3 I'm trying out OpenEJB. I followed their example about testing security but if I test in my code for the role with SessionContect.isCallerInRole() it always returns false.

Why doesn't it work?

I've written some code to illustrate.

My local interface:

@Local
public interface MyBean {

    boolean doSomething();

}

My EJB:

@Stateless
public class MyBeanImpl implements MyBean {

    @Resource
    private SessionContext sessionContext;

    @Override
    public boolean doSomething() {
        return this.sessionContext.isCallerInRole("role1");
    }

}

My test:

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();
        }

    }
}
1

There are 1 answers

0
Koohoolinn On BEST ANSWER

Well, apparently it's not supposed to work. It's part of the spec that @RunAs doesn't change the Principal's permissions.

I posted the same question on the OpenEJB forum (see it at Nabble) and got some more info there as well as a better solution.