可以从自定义LoginModule访问远程EJB吗?

时间:2010-05-05 11:53:05

标签: authentication java-ee glassfish ejb-3.0 glassfish-3

我找到了一些关于如何编写自定义域和loginModule的好提示。我想知道是否可以在自定义loginModule中访问远程EJB。

就我而言,我有远程EJB提供对用户实体的访问(通过JPA) - 我可以使用它们(例如通过@EJB注释)吗?

1 个答案:

答案 0 :(得分:3)

好的,我自己找到了答案:工作正常!我可以通过InitialContext获得对远程SLSB的引用。

以下是代码:

public class UserLoginModule extends AppservPasswordLoginModule {

    Logger log = Logger.getLogger(this.getClass().getName());

    private UserFacadeLocal userFacade;

    public UserLoginModule() {

        try {
            InitialContext ic = new InitialContext();
            userFacade = (UserFacadeLocal) ic.lookup("java:global/MyAppServer/UserFacade!com.skalio.myapp.beans.UserFacadeLocal");
            log.info("userFacade bean received");

        } catch (NamingException ex) {
            log.warning("Unable to get userFacade Bean!");
        }
    }

    @Override
    protected void authenticateUser() throws LoginException {
        log.fine("Attempting to authenticate user '"+ _username +"', '"+ _password +"'");

        User user;

        // get the realm
        UserRealm userRealm = (UserRealm) _currentRealm;

        try {
            user = userFacade.authenticate(_username, _password.trim());
            userFacade.detach(user);

        } catch (UnauthorizedException e) {
            log.warning("Authentication failed: "+ e.getMessage());
            throw new LoginException("UserLogin authentication failed!");

        } catch (Exception e) {
            throw new LoginException("UserLogin failed: "+ e.getMessage());

        }
        log.fine("Authentication successful for "+ user);

        // get the groups the user is a member of
        String[] grpList = userRealm.authorize(user);
        if (grpList == null) {
            throw new LoginException("User is not member of any groups");
        }

        // Add the logged in user to the subject's principals.
        // This works, but unfortunately, I can't reach the user object
        // afterwards again.
        Set principals = _subject.getPrincipals();
        principals.add(new UserPrincipalImpl(user));

        this.commitUserAuthentication(grpList);
    }

}

诀窍是将bean的接口与WAR分开。我将所有接口和公共实体捆绑在一个单独的OSGi模块中,并使用asadmin --type osgi进行部署。因此,自定义UserLoginModule可以加载它们。