2011-02-02 36 views
1

我需要編寫一個會話bean,在代碼中某處檢查當前用戶是否有某個角色。OpenEJB&JUnit:Sessioncontext.isCallerInRole返回allways false

單元測試我的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

嗯,顯然它不應該工作。這是@RunAs不會更改委託人權限的規範的一部分。

我在OpenEJB論壇上發佈了相同的問題(請參閱Nabble),並獲得了更多信息以及更好的解決方案。