是否可以在JSF + EJB中以编程方式设置Principal

时间:2012-12-10 22:16:08

标签: jsf ejb-3.0 ejb-3.1 jaas principal

我想使用EJBContext.getCallerPrincipal()

检索用户名
public class GlobalInterceptor {

    @EJB
    private  AuditLogsEJB auditLogsEJB;

    @Resource
    private EJBContext context;

    @AroundInvoke
    public Object auditLog(InvocationContext invocationContext) throws Exception
    {  
          System.out.println(context.getCallerPrincipal());  //it outputs "ANONYMOUS"
    }
}

但是我没有任何安全领域,我没有任何< security-role>或< group-name>定义因为用户名/密码被发送到远程应用程序进行验证。但为方便起见,我仍然希望使用Principal类来获取用户名和角色。

有没有办法在JSF托管bean或任何EJB中以编程方式设置Principal(用户名和角色),以便拦截器可以检索它? e.g:

String role = authenticationWSPort.validate(username, password);
if(role != null) 
{
      Principal p = new Principal(username);
      p.getRoles.add(role);
      FacesContext.getCurrentInstance().blah-blah.blah-blah.addPrincipal(p);
      //I am looking for something similar to the 3 lines above
}
else
     // invalid username and password

1 个答案:

答案 0 :(得分:0)

显然,正确的方法是设置领域并使用它。

也许你可以创造&配置自己的Realm实现,在servlet中调用request.login(用户名,密码)之前,可以动态创建用户。

或者

如果你真的想要使用底层请求,它是可能的,但它是应用程序服务器特定的,并且类似于这样,假设你在基于tomcat(catalina)的容器中:

if (request instanceof RequestFacade) {
        Request unwrapped = null;
        RequestFacade rf = RequestFacade.class.cast(request);
        try {
            Field requestField = rf.getClass().getDeclaredField("request");
            requestField.setAccessible(true);
            unwrapped = Request.class.cast(requestField.get(rf));
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException ex) {
            unwrapped = null;
        }

        if (unwrapped != null) {
            unwrapped.setUserPrincipal(... your principal construction here ...);
        }
    }