Example usage for javax.security.auth Subject getPrincipals

List of usage examples for javax.security.auth Subject getPrincipals

Introduction

In this page you can find the example usage for javax.security.auth Subject getPrincipals.

Prototype

public Set<Principal> getPrincipals() 

Source Link

Document

Return the Set of Principals associated with this Subject .

Usage

From source file:org.josso.jb32.agent.JBossCatalinaNativeRealm.java

/**
 * Return the Principal associated with the specified username and
 * credentials, if there is one; otherwise return null.
 *
 * The method was completely rewritten since the overriden operation,
 * on succesfull authentication, sets as the authenticated Principal
 * a SimplePrincipal instantiated using the provided username.
 * The problem is that in JOSSO the username is a SSO Session Id, not
 * a username. So we need to set the SSOUser returned by the Gateway
 * as the authenticatd Principal.//from w  w  w .j  a v a 2 s. c o  m
 * Since the JaasSecurityManager caches the authenticated user using the
 * Principal referring to a JOSSO Session Id, we will need to map, for
 * example when roles are checked against the realm, a user Principal
 * back to its JOSSO Session Identifier Principal. This way the the user
 * and its roles can be retrieved correctly by the JaasSecurityManager.
 *
 * @param username Username of the Principal to look up
 * @param credentials Password or other credentials to use in
 * authenticating this username
 */
public Principal authenticate(String username, String credentials) {

    logger.debug("Begin authenticate, username=" + username);

    Principal principal = null;
    SSOUser ssoUser = null;
    Principal caller = (Principal) SecurityAssociationValve.userPrincipal.get();
    if (caller == null && username == null && credentials == null)
        return null;

    try {
        Context securityCtx = null;
        securityCtx = prepareENC();

        if (securityCtx == null) {
            logger.error("No security context for authenticate(String, String)");
            return null;
        }

        // Get the JBoss security manager from the ENC context
        SubjectSecurityManager securityMgr = (SubjectSecurityManager) securityCtx.lookup("securityMgr");
        if (!isSSODomain(securityMgr.getSecurityDomain())) {
            // This is not a SSO Security domain, let JBoss realm handle this ...
            return super.authenticate(username, credentials);
        }

        principal = new SimplePrincipal(username);
        char[] passwordChars = null;
        if (credentials != null)
            passwordChars = credentials.toCharArray();

        SSOIdentityManagerService im = Lookup.getInstance().lookupSSOAgent().getSSOIdentityManager();

        String requester = "";
        // Check for nulls ?
        SSOAgentRequest request = AbstractSSOAgent._currentRequest.get();
        if (request != null)
            requester = request.getRequester();
        else
            logger.warn("No SSO Agent request found in thread local variable, can't identify requester");

        ssoUser = im.findUserInSession(requester, username);

        if (ssoUser != null) {
            logger.debug("User: " + username + " is authenticated");

            Subject subject = new Subject();
            subject.getPrincipals().add(ssoUser);
            logger.warn("WARN Cannot identify requester!");
            SSORole[] ssoRolePrincipals = im.findRolesBySSOSessionId(requester, username);
            Group targetGrp = new BaseRoleImpl("Roles");
            for (int i = 0; i < ssoRolePrincipals.length; i++) {
                subject.getPrincipals().add(ssoRolePrincipals[i]);
                targetGrp.addMember(ssoRolePrincipals[i]); // Add user role to "Roles" group
            }
            // Add the "Roles" group to the Subject so that JBoss can fetch user roles.
            subject.getPrincipals().add(targetGrp);

            logger.debug("Authenticated Subject: " + subject);

            // Make the cache aware of the user-session association so that
            // it can handle correctly cache entry lookups.
            //_cachePolicy.attachSessionToUser(principal, ssoUser);

            // Instead of associating the Principal used for authenticating (which is a
            // session id), sets the authenticated principal to the SSOUser part of the
            // Subject returned by the Gateway.
            JBossSecurityAssociationActions.setPrincipalInfo(ssoUser, passwordChars, subject);

            // Get the CallerPrincipal mapping
            RealmMapping rm = (RealmMapping) securityCtx.lookup("realmMapping");
            Principal oldPrincipal = ssoUser;
            principal = rm.getPrincipal(oldPrincipal);
            logger.debug("Mapped from input principal: " + oldPrincipal + " to: " + principal);
            if (!principal.equals(oldPrincipal)) {
                _userPrincipalMap.put(principal, oldPrincipal);
            }

        } else {
            principal = null;
            logger.debug("User: " + username + " is NOT authenticated");
        }
    } catch (NamingException e) {
        principal = null;
        logger.error("Error during authenticate", e);
    } catch (SSOIdentityException e) {
        // Ignore this ... (user does not exist for this session)
        if (logger.isDebugEnabled()) {
            logger.debug(e.getMessage());
        }
        principal = null;
    } catch (Exception e) {
        logger.error("Session authentication failed : " + username, e);
        throw new RuntimeException("Fatal error authenticating session : " + e);
    }
    logger.debug("End authenticate, principal=" + ssoUser);
    return ssoUser;
}

From source file:backtype.storm.blobstore.BlobStoreAclHandler.java

private Set<String> constructUserFromPrincipals(Subject who) {
    Set<String> user = new HashSet<String>();
    if (who != null) {
        for (Principal p : who.getPrincipals()) {
            user.add(_ptol.toLocal(p));//from   www . j  a  v  a 2s .  c o  m
        }
    }
    return user;
}

From source file:backtype.storm.blobstore.BlobStoreAclHandler.java

private Set<String> getUserNamesFromSubject(Subject who) {
    Set<String> user = new HashSet<String>();
    if (who != null) {
        for (Principal p : who.getPrincipals()) {
            user.add(_ptol.toLocal(p));// w w w.  j a v  a  2s  .c o m
        }
    }
    return user;
}

From source file:org.atricore.idbus.capabilities.sso.main.sp.producers.SPNameIDManagementProducer.java

@Override
protected void doProcess(CamelMediationExchange exchange) throws Exception {
    //      try{/*  w  w w  .j  a  va2  s  . co  m*/
    CamelMediationMessage in = (CamelMediationMessage) exchange.getIn();
    ManageNameIDRequestType manageNameID = (ManageNameIDRequestType) in.getMessage().getContent();

    StatusType status = new StatusType();
    StatusCodeType statusCode = new StatusCodeType();
    statusCode.setValue(StatusCode.TOP_SUCCESS.getValue());
    status.setStatusCode(statusCode);

    boolean validated = true;
    StringBuffer secondaryErrorCode = new StringBuffer();

    try {
        manageNameID = validateManageNameID(manageNameID, secondaryErrorCode);
    } catch (SSORequestException e1) {
        logger.error("Error validating ManageNameIDRequest", e1);
        validated = false;
    }

    if (validated) {
        if (manageNameID.getTerminate() != null) {
            SubjectNameID subjectNameID = null;
            if (manageNameID.getNameID() != null) {
                subjectNameID = new SubjectNameID(manageNameID.getNameID().getValue(),
                        manageNameID.getNameID().getFormat());
                subjectNameID.setLocalName(manageNameID.getNameID().getSPProvidedID());
            } else {
                NameIDType decryptedNameID = null;
                SamlR2Encrypter encrypter = ((SSOSPMediator) channel.getIdentityMediator()).getEncrypter();
                try {
                    decryptedNameID = encrypter.decryptNameID(manageNameID.getEncryptedID());
                } catch (SamlR2EncrypterException e) {
                    //TODO should we throw RuntimeException?
                    throw new SSOException("NameID cannot be decrypted.", e);
                }
                subjectNameID = new SubjectNameID(decryptedNameID.getValue(), decryptedNameID.getFormat());
                subjectNameID.setLocalName(decryptedNameID.getSPProvidedID());
            }
            Subject idpSubject = new Subject();
            idpSubject.getPrincipals().add(subjectNameID);

            // check if there is an existing session for the user
            FederationChannel fChannel = (FederationChannel) channel;

            // if not, check if channel is federation-capable
            if (fChannel.getAccountLinkLifecycle() == null) {

                // cannot map subject to local account, terminate
                logger.error("No Account Lifecycle configured for Channel [" + fChannel.getName() + "] "
                        + " ManageNameID [" + manageNameID.getID() + "]");
                throw new SSOException("No Account Lifecycle configured for Channel [" + fChannel.getName()
                        + "] " + " ManageNameID [" + manageNameID.getID() + "]");
            }

            AccountLinkLifecycle accountLinkLifecycle = fChannel.getAccountLinkLifecycle();
            AccountLink accountLink = accountLinkLifecycle.findByIDPAccount(idpSubject);
            if (accountLink == null) {
                logger.error("No Account Link available for Principal [" + subjectNameID.getName() + "]");
                throw new SSOException(
                        "No Account Link available for Principal [" + subjectNameID.getName() + "]");
            }
            accountLinkLifecycle.dispose(accountLink);
        }
    }

    // ---------------------------------------------------
    // Send ManageNameIDResponse
    // ---------------------------------------------------

    CircleOfTrustMemberDescriptor idp = this.resolveIdp();
    logger.debug("Using IDP " + idp.getAlias());

    // Select endpoint, must be a ManageNameIDService endpoint
    EndpointType idpSsoEndpoint = resolveIdpMNIDEndpoint(idp);
    EndpointDescriptor destination = new EndpointDescriptorImpl("IDPMNIEndpoint", "ManageNameIDService",
            idpSsoEndpoint.getBinding(), idpSsoEndpoint.getLocation(), idpSsoEndpoint.getResponseLocation());

    StatusResponseType mnidResponse = buildMNIDResponse(exchange, idp, idpSsoEndpoint, validated,
            secondaryErrorCode.toString());

    CamelMediationMessage out = (CamelMediationMessage) exchange.getOut();
    out.setMessage(new MediationMessageImpl(mnidResponse.getID(), mnidResponse, "ManageNameIDResponse", null,
            destination, in.getMessage().getState()));

    exchange.setOut(out);
}

From source file:org.josso.tc50.agent.jaas.CatalinaJAASRealm.java

/**
 * Construct and return a java.security.Principal instance
 * representing the authenticated user for the specified Subject.  If no
 * such Principal can be constructed, return null.
 *
 * The Principal constructed is *not* GenericPrincipal as in Catalina JAASRealm class,
 * but CatalinaSSOUser which is a SSOUser.
 * The Partner Application can access SSOUser-specific properties that are not available
 * in GenericPrincipal./*w w w  .  j  a  v a  2  s  .  co  m*/
 * The JAASRealm superclass invokes this factory method to build the Catalina-specific
 * Principal from the Subject filled by the configured JAASLoginModule.
 *
 * @param subject The Subject representing the logged in user
 */
protected Principal createPrincipal(String username, Subject subject) {

    // We also populate roles map ...

    CatalinaSSOUser p = CatalinaSSOUser.newInstance(this, subject);

    if (requiresRoleMap) {
        // This is a Tomcat 5.0.30 ... !

        try {

            List<Principal> roles = new ArrayList<Principal>();

            Iterator principals = subject.getPrincipals().iterator();
            while (principals.hasNext()) {

                Principal principal = (Principal) principals.next();
                String principalClass = principal.getClass().getName();

                if (getRoleClassNames().contains(principalClass)) {
                    log.debug("Adding role : " + principal.getName());
                    roles.add(principal);
                }

                // Same as Jboss - that's a pretty clean solution
                if ((principal instanceof Group) && "Roles".equals(principal.getName())) {
                    Group grp = (Group) principal;
                    Enumeration en = grp.members();
                    while (en.hasMoreElements()) {
                        Principal roleP = (Principal) en.nextElement();
                        log.debug("Adding role : " + roleP.getName());
                        roles.add(roleP);
                    }

                }
            }

            // Only in Catalina 5.0.30!
            log.debug("Storing roles in parent roleMap");
            Map m = (Map) getRoleMapField().get(this);
            m.put(p, roles);

        } catch (Exception e) {
            log.warn(e.getMessage(), e);
            return p;
        }

    }

    return p;

}

From source file:org.apache.karaf.jaas.modules.ldap.GSSAPILdapLoginModuleTest.java

@Test(expected = LoginException.class)
public void testUsernameFailure() throws Exception {

    Properties options = ldapLoginModuleOptions();
    GSSAPILdapLoginModule module = new GSSAPILdapLoginModule();

    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("hnelson0");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("secret".toCharArray());
                }//w  w  w.  j a v  a  2 s.c o  m
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login()); // should throw LoginException
}

From source file:org.apache.karaf.jaas.modules.ldap.GSSAPILdapLoginModuleTest.java

@Test(expected = LoginException.class)
public void testPasswordFailure() throws Exception {

    Properties options = ldapLoginModuleOptions();
    GSSAPILdapLoginModule module = new GSSAPILdapLoginModule();

    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("hnelson");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("secret0".toCharArray());
                }//from   w  ww .  java 2  s  .c om
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login());
}

From source file:org.apache.karaf.jaas.modules.ldap.GSSAPILdapLoginModuleTest.java

@Test(expected = LoginException.class)
public void testUserNotFound() throws Exception {

    Properties options = ldapLoginModuleOptions();
    GSSAPILdapLoginModule module = new GSSAPILdapLoginModule();

    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("test");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("test".toCharArray());
                }/*w w w  .j a  va  2s.com*/
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertFalse(module.login());
}

From source file:org.apache.karaf.jaas.modules.ldap.GSSAPILdapLoginModuleTest.java

@Test(expected = LoginException.class)
public void testNoRealm() throws Exception {

    Properties options = ldapLoginModuleOptions();
    options.remove(GSSAPILdapLoginModule.REALM_PROPERTY);
    GSSAPILdapLoginModule module = new GSSAPILdapLoginModule();

    CallbackHandler cb = new CallbackHandler() {
        public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
            for (Callback cb : callbacks) {
                if (cb instanceof NameCallback) {
                    ((NameCallback) cb).setName("hnelson0");
                } else if (cb instanceof PasswordCallback) {
                    ((PasswordCallback) cb).setPassword("secret".toCharArray());
                }//from   w  ww .j a  va  2  s  .  c o  m
            }
        }
    };
    Subject subject = new Subject();
    module.initialize(subject, cb, null, options);

    assertEquals("Precondition", 0, subject.getPrincipals().size());
    assertTrue(module.login()); // should throw LoginException
}

From source file:org.josso.gl2.agent.jaas.CatalinaJAASRealm.java

/**
 * Construct and return a java.security.Principal instance
 * representing the authenticated user for the specified Subject.  If no
 * such Principal can be constructed, return null.
 *
 * The Principal constructed is *not* GenericPrincipal as in Catalina JAASRealm class,
 * but CatalinaSSOUser which is a SSOUser.
 * The Partner Application can access SSOUser-specific properties that are not available
 * in GenericPrincipal./*  w w w  . j av  a 2 s  . c o  m*/
 * The JAASRealm superclass invokes this factory method to build the Catalina-specific
 * Principal from the Subject filled by the configured JAASLoginModule.
 *
 * @param subject The Subject representing the logged in user
 */
@Override
protected Principal createPrincipal(String username, Subject subject) {

    // We also populate roles map ...

    CatalinaSSOUser p = CatalinaSSOUser.newInstance(this, subject);

    if (requiresRoleMap) {
        // This is a Tomcat 5.0.30 ... !

        try {

            List<Principal> roles = new ArrayList<Principal>();

            Iterator principals = subject.getPrincipals().iterator();
            while (principals.hasNext()) {

                Principal principal = (Principal) principals.next();
                String principalClass = principal.getClass().getName();

                if (getRoleClassNames().contains(principalClass)) {
                    log.debug("Adding role : " + principal.getName());
                    roles.add(principal);
                }

                // Same as Jboss - that's a pretty clean solution
                if ((principal instanceof Group) && "Roles".equals(principal.getName())) {
                    Group grp = (Group) principal;
                    Enumeration en = grp.members();
                    while (en.hasMoreElements()) {
                        Principal roleP = (Principal) en.nextElement();
                        log.debug("Adding role : " + roleP.getName());
                        roles.add(roleP);
                    }

                }
            }

            // Only in Catalina 5.0.30!
            log.debug("Storing roles in parent roleMap");
            Map m = (Map) getRoleMapField().get(this);
            m.put(p, roles);

        } catch (Exception e) {
            log.warn(e.getMessage(), e);
            return p;
        }

    }

    return p;

}