Search in sources :

Example 21 with NameID

use of com.sun.identity.saml2.assertion.NameID in project OpenAM by OpenRock.

the class IDPSSOUtil method getSubject.

/**
     * Returns a <code>SAML Subject</code> object
     *
     * @param session           the user's session
     * @param authnReq          the <code>AuthnRequest</code> object
     * @param acsURL            the <code>ACS</code> service <code>url</code>
     * @param nameIDFormat      the <code>NameIDFormat</code>
     * @param realm             The realm name
     * @param idpEntityID       the entity id of the identity provider
     * @param recipientEntityID the entity id of the response recipient
     * @param effectiveTime     the effective time of the assertion
     * @param affiliationID     affiliationID for IDP initiated SSO
     * @return the <code>SAML Subject</code> object
     * @throws SAML2Exception if the operation is not successful
     */
private static Subject getSubject(Object session, AuthnRequest authnReq, String acsURL, String nameIDFormat, String realm, String idpEntityID, String recipientEntityID, int effectiveTime, String affiliationID) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.getSubject: ";
    Subject subject = AssertionFactory.getInstance().createSubject();
    boolean ignoreProfile = false;
    String userName = null;
    try {
        userName = sessionProvider.getPrincipalName(session);
        ignoreProfile = SAML2Utils.isIgnoreProfileSet(session);
    } catch (SessionException se) {
        SAML2Utils.debug.error(classMethod + "There was a problem with the session.", se);
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
    }
    // allow create is the default
    boolean allowCreate = true;
    String remoteEntityID = null;
    String spNameQualifier = null;
    boolean isAffiliation = false;
    if (authnReq != null) {
        remoteEntityID = authnReq.getIssuer().getValue();
        NameIDPolicy nameIDPolicy = authnReq.getNameIDPolicy();
        if (nameIDPolicy != null) {
            // this will take care of affiliation
            allowCreate = nameIDPolicy.isAllowCreate();
            spNameQualifier = nameIDPolicy.getSPNameQualifier();
            if (spNameQualifier != null && !spNameQualifier.isEmpty()) {
                AffiliationDescriptorType affiDesc = metaManager.getAffiliationDescriptor(realm, spNameQualifier);
                if (affiDesc != null) {
                    if (affiDesc.getAffiliateMember().contains(remoteEntityID)) {
                        isAffiliation = true;
                        remoteEntityID = spNameQualifier;
                    } else {
                        throw new SAML2Exception(SAML2Utils.bundle.getString("spNotAffiliationMember"));
                    }
                }
            } else {
                spNameQualifier = recipientEntityID;
            }
        }
    } else {
        // IDP initialted SSO
        if (affiliationID != null) {
            AffiliationDescriptorType affiDesc = metaManager.getAffiliationDescriptor(realm, affiliationID);
            if (affiDesc == null) {
                throw new SAML2Exception(SAML2Utils.bundle.getString("affiliationNotFound"));
            }
            if (affiDesc.getAffiliateMember().contains(recipientEntityID)) {
                isAffiliation = true;
                remoteEntityID = affiliationID;
                spNameQualifier = affiliationID;
            } else {
                throw new SAML2Exception(SAML2Utils.bundle.getString("spNotAffiliationMember"));
            }
        } else {
            remoteEntityID = recipientEntityID;
            spNameQualifier = recipientEntityID;
        }
    }
    SPSSODescriptorElement spsso = getSPSSODescriptor(realm, recipientEntityID, classMethod);
    if (spsso == null) {
        String[] data = { recipientEntityID };
        LogUtil.error(Level.INFO, LogUtil.SP_METADATA_ERROR, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
    IDPSSODescriptorElement idpsso = metaManager.getIDPSSODescriptor(realm, idpEntityID);
    if (idpsso == null) {
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
    nameIDFormat = SAML2Utils.verifyNameIDFormat(nameIDFormat, spsso, idpsso);
    boolean isTransient = SAML2Constants.NAMEID_TRANSIENT_FORMAT.equals(nameIDFormat);
    boolean isPersistent = SAML2Constants.PERSISTENT.equals(nameIDFormat);
    NameIDInfo nameIDInfo;
    NameID nameID = null;
    IDPAccountMapper idpAccountMapper = SAML2Utils.getIDPAccountMapper(realm, idpEntityID);
    //Use-cases for NameID persistence:
    //* persistent NameID -> The NameID MUST be stored
    //* transient NameID -> The NameID MUST NOT be stored
    //* ignored user profile mode -> The NameID CANNOT be stored
    //* for any other cases -> The NameID MAY be stored based on customizable logic
    boolean shouldPersistNameID = isPersistent || (!isTransient && !ignoreProfile && idpAccountMapper.shouldPersistNameIDFormat(realm, idpEntityID, remoteEntityID, nameIDFormat));
    if (!isTransient) {
        String userID;
        try {
            userID = sessionProvider.getPrincipalName(session);
        } catch (SessionException se) {
            SAML2Utils.debug.error(classMethod + "Unable to get principal name from the session.", se);
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
        }
        if (isPersistent || shouldPersistNameID) {
            nameIDInfo = AccountUtils.getAccountFederation(userID, idpEntityID, remoteEntityID);
            if (nameIDInfo != null) {
                nameID = nameIDInfo.getNameID();
                if (!nameIDFormat.equals(nameID.getFormat())) {
                    AccountUtils.removeAccountFederation(nameIDInfo, userID);
                    DoManageNameID.removeIDPFedSession(remoteEntityID, nameID.getValue());
                    nameID = null;
                }
            }
        }
    }
    if (nameID == null) {
        if (!allowCreate && isPersistent) {
            throw new SAML2InvalidNameIDPolicyException(SAML2Utils.bundle.getString("cannotCreateNameID"));
        }
        nameID = idpAccountMapper.getNameID(session, idpEntityID, spNameQualifier, realm, nameIDFormat);
        SAML2Utils.debug.message(classMethod + " shouldPersistNameID = " + shouldPersistNameID);
        if (shouldPersistNameID && allowCreate) {
            // write federation info into the persistent datastore
            if (SAML2Utils.isDualRole(idpEntityID, realm)) {
                nameIDInfo = new NameIDInfo(idpEntityID, remoteEntityID, nameID, SAML2Constants.DUAL_ROLE, false);
            } else {
                nameIDInfo = new NameIDInfo(idpEntityID, remoteEntityID, nameID, SAML2Constants.IDP_ROLE, isAffiliation);
            }
            AccountUtils.setAccountFederation(nameIDInfo, userName);
        }
    }
    subject.setNameID(nameID);
    if (isTransient) {
        IDPCache.userIDByTransientNameIDValue.put(nameID.getValue(), userName);
    }
    String inResponseTo = null;
    if (authnReq != null) {
        inResponseTo = authnReq.getID();
    }
    SubjectConfirmation sc = getSubjectConfirmation(inResponseTo, acsURL, effectiveTime);
    if (sc == null) {
        SAML2Utils.debug.error(classMethod + "Unable to get subject confirmation");
        throw new SAML2Exception(SAML2Utils.bundle.getString("noSubjectConfirmation"));
    }
    List list = new ArrayList();
    list.add(sc);
    subject.setSubjectConfirmation(list);
    return subject;
}
Also used : NameIDInfo(com.sun.identity.saml2.common.NameIDInfo) IDPAccountMapper(com.sun.identity.saml2.plugins.IDPAccountMapper) NameIDPolicy(com.sun.identity.saml2.protocol.NameIDPolicy) NameID(com.sun.identity.saml2.assertion.NameID) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) ArrayList(java.util.ArrayList) SessionException(com.sun.identity.plugin.session.SessionException) AffiliationDescriptorType(com.sun.identity.saml2.jaxb.metadata.AffiliationDescriptorType) Subject(com.sun.identity.saml2.assertion.Subject) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SubjectConfirmation(com.sun.identity.saml2.assertion.SubjectConfirmation) List(java.util.List) ArrayList(java.util.ArrayList) SAML2InvalidNameIDPolicyException(com.sun.identity.saml2.common.SAML2InvalidNameIDPolicyException) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 22 with NameID

use of com.sun.identity.saml2.assertion.NameID in project OpenAM by OpenRock.

the class IDPSSOUtil method getAssertion.

/**
     * Returns a <code>SAML Assertion</code> object
     *
     * @throws SAML2Exception if the operation is not successful
     * @param request The HTTP request.
     * @param session The user's session object.
     * @param authnReq The <code>AuthnRequest</code> object.
     * @param recipientEntityID The entity ID of the response recipient.
     * @param idpEntityID The entity ID of the identity provider.
     * @param realm The realm name.
     * @param nameIDFormat The <code>NameIDFormat</code>.
     * @param acsURL The <code>ACS</code> service <code>url</code>.
     * @param affiliationID AffiliationID for IDP initiated SSO.
     * @param matchingAuthnContext the <code>AuthnContext</code> used to find authentication type and scheme.
     * @return the <code>SAML Assertion</code> object.
     * @throws SAML2Exception if the operation is not successful.
     */
private static Assertion getAssertion(HttpServletRequest request, Object session, AuthnRequest authnReq, String recipientEntityID, String idpEntityID, String idpMetaAlias, String realm, String nameIDFormat, String acsURL, String affiliationID, AuthnContext matchingAuthnContext) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.getAssertion: ";
    Assertion assertion = AssertionFactory.getInstance().createAssertion();
    String assertionID = SAML2Utils.generateID();
    assertion.setID(assertionID);
    assertion.setVersion(SAML2Constants.VERSION_2_0);
    assertion.setIssueInstant(new Date());
    Issuer issuer = AssertionFactory.getInstance().createIssuer();
    issuer.setValue(idpEntityID);
    assertion.setIssuer(issuer);
    List statementList = new ArrayList();
    NewBoolean isNewSessionIndex = new NewBoolean();
    AuthnStatement authnStatement = null;
    IDPSession idpSession = null;
    String sessionIndex = null;
    String sessionID = sessionProvider.getSessionID(session);
    synchronized (sessionID) {
        authnStatement = getAuthnStatement(request, session, isNewSessionIndex, authnReq, idpEntityID, realm, matchingAuthnContext);
        if (authnStatement == null) {
            return null;
        }
        sessionIndex = authnStatement.getSessionIndex();
        if (isNewSessionIndex.getValue()) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "This is a new IDP session with sessionIndex=" + sessionIndex + ", and sessionID=" + sessionID);
            }
            idpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(sessionProvider.getSessionID(session));
            if (idpSession == null) {
                idpSession = new IDPSession(session);
            }
            // Set the metaAlias in the IDP session object
            idpSession.setMetaAlias(idpMetaAlias);
            IDPCache.idpSessionsByIndices.put(sessionIndex, idpSession);
            if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsByIndices.size());
            }
        } else {
            idpSession = (IDPSession) IDPCache.idpSessionsByIndices.get(sessionIndex);
        }
    }
    if (isNewSessionIndex.getValue()) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "a new IDP session has been saved in cache, " + "with sessionIndex=" + sessionIndex);
        }
        try {
            sessionProvider.addListener(session, sessionListener);
        } catch (SessionException e) {
            SAML2Utils.debug.error(classMethod + "Unable to add session listener.");
        }
    } else {
        if (idpSession == null && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            // Read from SAML2 Token Repository
            IDPSessionCopy idpSessionCopy = null;
            try {
                idpSessionCopy = (IDPSessionCopy) SAML2FailoverUtils.retrieveSAML2Token(sessionIndex);
            } catch (SAML2TokenRepositoryException se) {
                SAML2Utils.debug.error(classMethod + "Unable to obtain IDPSessionCopy from the SAML2 Token Repository for sessionIndex:" + sessionIndex, se);
            }
            // Copy back to IDPSession
            if (idpSessionCopy != null) {
                idpSession = new IDPSession(idpSessionCopy);
            } else {
                SAML2Utils.debug.error("IDPSessionCopy is null");
                throw new SAML2Exception(SAML2Utils.bundle.getString("IDPSessionIsNULL"));
            }
        } else if ((idpSession == null) && (!SAML2FailoverUtils.isSAML2FailoverEnabled())) {
            SAML2Utils.debug.error("IDPSession is null; SAML2 failover" + "is disabled");
            throw new SAML2Exception(SAML2Utils.bundle.getString("IDPSessionIsNULL"));
        } else {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "This is an existing IDP session with sessionIndex=" + sessionIndex + ", and sessionID=" + sessionProvider.getSessionID(idpSession.getSession()));
            }
        }
    }
    statementList.add(authnStatement);
    AttributeStatement attrStatement = getAttributeStatement(session, idpEntityID, recipientEntityID, realm);
    if (attrStatement != null) {
        List attrStatementList = new ArrayList();
        attrStatementList.add(attrStatement);
        assertion.setAttributeStatements(attrStatementList);
    }
    // get the assertion effective time (in seconds)
    int effectiveTime = getEffectiveTime(realm, idpEntityID);
    // get the NotBefore skew (in seconds)
    int notBeforeSkewTime = getNotBeforeSkewTime(realm, idpEntityID);
    // get the subject element
    Subject subject = getSubject(session, authnReq, acsURL, nameIDFormat, realm, idpEntityID, recipientEntityID, effectiveTime, affiliationID);
    // register (spEntityID, nameID) with the sso token
    // for later logout use 
    String spEntityID = null;
    if (authnReq != null) {
        spEntityID = authnReq.getIssuer().getValue();
    } else {
        spEntityID = recipientEntityID;
    }
    NameIDandSPpair pair = new NameIDandSPpair(subject.getNameID(), spEntityID);
    synchronized (IDPCache.idpSessionsByIndices) {
        List<NameIDandSPpair> list = idpSession.getNameIDandSPpairs();
        String id;
        if (authnReq != null) {
            id = authnReq.getIssuer().getValue();
        } else {
            id = spEntityID;
        }
        boolean found = false;
        for (NameIDandSPpair nameIDandSPpair : list) {
            if (nameIDandSPpair.getSPEntityID().equals(id)) {
                found = true;
                break;
            }
        }
        if (!found) {
            list.add(pair);
        }
    }
    assertion.setAuthnStatements(statementList);
    assertion.setSubject(subject);
    Conditions conditions = getConditions(recipientEntityID, notBeforeSkewTime, effectiveTime);
    assertion.setConditions(conditions);
    String discoBootstrapEnabled = getAttributeValueFromIDPSSOConfig(realm, idpEntityID, SAML2Constants.DISCO_BOOTSTRAPPING_ENABLED);
    if ((discoBootstrapEnabled != null) && discoBootstrapEnabled.equalsIgnoreCase("true")) {
        List attrStatementList = assertion.getAttributeStatements();
        if (attrStatementList == null) {
            attrStatementList = new ArrayList();
            assertion.setAttributeStatements(attrStatementList);
        }
        DiscoveryBootstrap bootstrap = new DiscoveryBootstrap(session, subject, authnStatement.getAuthnContext().getAuthnContextClassRef(), spEntityID, realm);
        attrStatementList.add(bootstrap.getBootstrapStatement());
        assertion.setAdvice(bootstrap.getCredentials());
    }
    if (assertionCacheEnabled(realm, idpEntityID)) {
        String userName = null;
        try {
            userName = sessionProvider.getPrincipalName(session);
        } catch (SessionException se) {
            SAML2Utils.debug.error(classMethod + "Unable to get principal name from the session.", se);
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
        }
        String cacheKey = userName.toLowerCase();
        List assertions = (List) IDPCache.assertionCache.get(cacheKey);
        if (assertions == null) {
            synchronized (IDPCache.assertionCache) {
                assertions = (List) IDPCache.assertionCache.get(cacheKey);
                if (assertions == null) {
                    assertions = new ArrayList();
                    IDPCache.assertionCache.put(cacheKey, assertions);
                }
            }
        }
        synchronized (assertions) {
            assertions.add(assertion);
        }
        IDPCache.assertionByIDCache.put(assertionID, assertion);
        if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            try {
                SAML2FailoverUtils.saveSAML2Token(assertionID, cacheKey, assertion.toXMLString(true, true), conditions.getNotOnOrAfter().getTime() / 1000);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "Saving Assertion to SAML2 Token Repository. ID = " + assertionID);
                }
            } catch (SAML2TokenRepositoryException se) {
                SAML2Utils.debug.error(classMethod + "Unable to save Assertion to the SAML2 Token Repository", se);
            }
        }
    }
    //  Save to SAML2 Token Repository
    try {
        if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            long sessionExpireTime = System.currentTimeMillis() / 1000 + (sessionProvider.getTimeLeft(session));
            SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(sessionIndex, new IDPSessionCopy(idpSession), sessionExpireTime);
        }
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "SAVE IDPSession!");
        }
    } catch (SessionException se) {
        SAML2Utils.debug.error(classMethod + "Unable to get left-time from the session.", se);
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
    } catch (SAML2TokenRepositoryException se) {
        SAML2Utils.debug.error(classMethod + "Unable to save IDPSession to the SAML2 Token Repository", se);
    }
    return assertion;
}
Also used : Issuer(com.sun.identity.saml2.assertion.Issuer) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) ArrayList(java.util.ArrayList) NewBoolean(com.sun.identity.saml2.common.NewBoolean) SessionException(com.sun.identity.plugin.session.SessionException) Date(java.util.Date) Subject(com.sun.identity.saml2.assertion.Subject) Conditions(com.sun.identity.saml2.assertion.Conditions) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement) AuthnStatement(com.sun.identity.saml2.assertion.AuthnStatement) List(java.util.List) ArrayList(java.util.ArrayList) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)

Example 23 with NameID

use of com.sun.identity.saml2.assertion.NameID in project OpenAM by OpenRock.

the class DoManageNameID method processManageNameIDRequest.

private static Status processManageNameIDRequest(ManageNameIDRequest mniRequest, String realm, String hostEntityID, String remoteEntityID, String hostRole, String userID) throws Exception {
    String method = "processManageNameIDRequest: ";
    if (debug.messageEnabled()) {
        debug.message(method + "Host EntityID is : " + hostEntityID);
        debug.message(method + "Host role is : " + hostRole);
        debug.message(method + "Realm  is : " + realm);
    }
    NameID nameID = getNameIDFromMNIRequest(mniRequest, realm, hostEntityID, hostRole);
    NameIDInfo oldNameIDInfo = getNameIDInfo(userID, hostEntityID, remoteEntityID, hostRole, realm, nameID.getSPNameQualifier(), true);
    NameID oldNameID = null;
    if (oldNameIDInfo != null) {
        oldNameID = oldNameIDInfo.getNameID();
    }
    if (oldNameID == null) {
        // log manage name id failure
        logError("unknownPrinciapl", LogUtil.UNKNOWN_PRINCIPAL, mniRequest.toXMLString(true, true));
        return SAML2Utils.generateStatus(SAML2Constants.REQUESTER, SAML2Constants.UNKNOWN_PRINCIPAL, null);
    }
    List spFedSessions = null;
    IDPSession idpSession = null;
    // Terminate
    if (hostRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
        idpSession = removeIDPFedSession(remoteEntityID, oldNameID.getValue());
    } else {
        spFedSessions = (List) SPCache.fedSessionListsByNameIDInfoKey.remove(oldNameIDInfo.getNameIDInfoKey().toValueString());
        if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
            saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
        }
    }
    if (!AccountUtils.removeAccountFederation(oldNameIDInfo, userID)) {
        // log termination failure
        logError("unableToTerminate", LogUtil.UNABLE_TO_TERMINATE, userID);
        return SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("unableToTerminate"));
    }
    if (mniRequest.getTerminate()) {
        // log termination success
        logAccess("requestSuccess", LogUtil.SUCCESS_FED_TERMINATION, userID);
        return SAML2Utils.generateStatus(SAML2Constants.SUCCESS, SAML2Utils.bundle.getString("requestSuccess"));
    }
    // newID case
    NewID newID = getNewIDFromMNIRequest(mniRequest, realm, hostEntityID, hostRole);
    boolean isAffiliation = oldNameIDInfo.isAffiliation();
    String spNameQualifier = oldNameID.getSPNameQualifier();
    if (hostRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
        NameID newNameID = AssertionFactory.getInstance().createNameID();
        newNameID.setValue(oldNameID.getValue());
        newNameID.setNameQualifier(oldNameID.getNameQualifier());
        newNameID.setSPNameQualifier(spNameQualifier);
        newNameID.setFormat(oldNameID.getFormat());
        newNameID.setSPProvidedID(newID.getValue());
        NameIDInfo newNameIDinfo = new NameIDInfo(hostEntityID, (isAffiliation ? spNameQualifier : remoteEntityID), newNameID, SAML2Constants.IDP_ROLE, isAffiliation);
        AccountUtils.setAccountFederation(newNameIDinfo, userID);
        if (idpSession != null) {
            // there are active session using this Name id
            NameIDandSPpair pair = new NameIDandSPpair(newNameID, remoteEntityID);
            synchronized (IDPCache.idpSessionsByIndices) {
                List list = (List) idpSession.getNameIDandSPpairs();
                list.add(pair);
            }
        }
        // log new name id success
        logAccess("requestSuccess", LogUtil.SUCCESS_NEW_NAMEID, userID);
        return SAML2Utils.generateStatus(SAML2Constants.SUCCESS, SAML2Utils.bundle.getString("requestSuccess"));
    }
    // SP ROLE
    NameID newNameID = AssertionFactory.getInstance().createNameID();
    newNameID.setValue(newID.getValue());
    newNameID.setNameQualifier(oldNameID.getNameQualifier());
    newNameID.setSPProvidedID(oldNameID.getSPProvidedID());
    newNameID.setSPNameQualifier(spNameQualifier);
    newNameID.setFormat(oldNameID.getFormat());
    NameIDInfo newNameIDInfo = new NameIDInfo((isAffiliation ? spNameQualifier : hostEntityID), remoteEntityID, newNameID, hostRole, isAffiliation);
    AccountUtils.setAccountFederation(newNameIDInfo, userID);
    if (spFedSessions != null) {
        String newInfoKeyStr = newNameIDInfo.getNameIDInfoKey().toValueString();
        String infoKeyAttribute = AccountUtils.getNameIDInfoKeyAttribute();
        synchronized (spFedSessions) {
            for (Iterator iter = spFedSessions.iterator(); iter.hasNext(); ) {
                SPFedSession spFedSession = (SPFedSession) iter.next();
                spFedSession.info = newNameIDInfo;
                String tokenID = spFedSession.spTokenID;
                try {
                    Object session = sessionProvider.getSession(tokenID);
                    String[] fromToken = sessionProvider.getProperty(session, infoKeyAttribute);
                    if ((fromToken == null) || (fromToken.length == 0) || (fromToken[0] == null) || (fromToken[0].length() == 0)) {
                        String[] values = { newInfoKeyStr };
                        sessionProvider.setProperty(session, infoKeyAttribute, values);
                    } else {
                        if (fromToken[0].indexOf(newInfoKeyStr) == -1) {
                            String[] values = { fromToken[0] + SAML2Constants.SECOND_DELIM + newInfoKeyStr };
                            sessionProvider.setProperty(session, infoKeyAttribute, values);
                        }
                    }
                } catch (SessionException ex) {
                    debug.error("DoManageNameID." + "processManageNameIDRequest:", ex);
                }
            }
        }
        SPCache.fedSessionListsByNameIDInfoKey.put(newInfoKeyStr, spFedSessions);
        if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
            saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
        }
    }
    // log new name id success
    logAccess("requestSuccess", LogUtil.SUCCESS_NEW_NAMEID, userID);
    return SAML2Utils.generateStatus(SAML2Constants.SUCCESS, SAML2Utils.bundle.getString("requestSuccess"));
}
Also used : NewID(com.sun.identity.saml2.protocol.NewID) NameIDInfo(com.sun.identity.saml2.common.NameIDInfo) NameID(com.sun.identity.saml2.assertion.NameID) SessionException(com.sun.identity.plugin.session.SessionException) Iterator(java.util.Iterator) List(java.util.List)

Example 24 with NameID

use of com.sun.identity.saml2.assertion.NameID in project OpenAM by OpenRock.

the class IDPSSOUtil method signAndEncryptResponseComponents.

/**
     * Signs and encrypts the components of a <code>SAML Response</code>
     * based on the service provider meta data. If the flag of
     * encrypting <code>Assertion</code> is on, then the embedded
     * <code>Assertion</code> object will be encrypted; if the flag
     * of encrypting <code>Assertion</code> is off and the flag of
     * encrypting <code>NameID</code> is on, then the <code>NameID</code>
     * embedded in the <code>Assertion</code> will be encrypted; if the
     * flag of encrypting <code>Assertion</code> is off and the flag of
     * encrypting <code>Attribute</code> is on, then the
     * <code>Attribute</code> embedded in the <code>Assertion</code>
     * will be encrypted. If the flag signAssertion is on, then the
     * <code>Assertion</code> will be signed. It will be signed before
     * it is encrypted and after its embedded <code>NameID</code> or
     * <code>Attribute</code> is encrypted.
     *
     * @param realm         the realm name of the identity provider
     * @param spEntityID    the entity id of the service provider
     * @param idpEntityID   the entity id of the identity provider
     * @param res           The <code>Response</code> whose components may be
     *                      encrypted based on the service provider meta data setting
     * @param signAssertion A flag to indicate if <code>Assertion</code>
     *                      signing is required
     */
static void signAndEncryptResponseComponents(String realm, String spEntityID, String idpEntityID, Response res, boolean signAssertion) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.signAndEncryptResponseComponents: ";
    boolean toEncryptAssertion = false;
    boolean toEncryptNameID = false;
    boolean toEncryptAttribute = false;
    if (res == null) {
        return;
    }
    List assertions = res.getAssertion();
    if ((assertions == null) || (assertions.size() == 0)) {
        return;
    }
    Assertion assertion = (Assertion) assertions.get(0);
    // get the encryption related flags from the SP Entity Config
    String wantAssertionEncrypted = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
    toEncryptAssertion = (wantAssertionEncrypted != null) && (wantAssertionEncrypted.equals(SAML2Constants.TRUE));
    if (!toEncryptAssertion) {
        String wantNameIDEncrypted = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_NAMEID_ENCRYPTED);
        toEncryptNameID = (wantNameIDEncrypted != null) && (wantNameIDEncrypted.equals(SAML2Constants.TRUE));
        String wantAttributeEncrypted = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_ATTRIBUTE_ENCRYPTED);
        toEncryptAttribute = (wantAttributeEncrypted != null) && (wantAttributeEncrypted.equals(SAML2Constants.TRUE));
    }
    if ((!toEncryptAssertion) && (!toEncryptNameID) && (!toEncryptAttribute)) {
        // all encryption flags are off, no encryption needed
        if (signAssertion) {
            signAssertion(realm, idpEntityID, assertion);
            List assertionList = new ArrayList();
            assertionList.add(assertion);
            res.setAssertion(assertionList);
        }
        return;
    }
    SPSSODescriptorElement spSSODescriptorElement = getSPSSODescriptor(realm, spEntityID, classMethod);
    // get the encryption information
    EncInfo encInfo = KeyUtil.getEncInfo(spSSODescriptorElement, spEntityID, SAML2Constants.SP_ROLE);
    if (encInfo == null) {
        SAML2Utils.debug.error(classMethod + "failed to get service provider encryption key info.");
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableToFindEncryptKeyInfo"));
    }
    if (toEncryptAssertion) {
        // sign assertion first, then encrypt the assertion
        if (signAssertion) {
            signAssertion(realm, idpEntityID, assertion);
        }
        // we only encrypt the Assertion
        EncryptedAssertion encryptedAssertion = assertion.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), spEntityID);
        if (encryptedAssertion == null) {
            SAML2Utils.debug.error(classMethod + "failed to encrypt the assertion.");
            throw new SAML2Exception(SAML2Utils.bundle.getString("FailedToEncryptAssertion"));
        }
        List assertionList = new ArrayList();
        assertionList.add(encryptedAssertion);
        res.setEncryptedAssertion(assertionList);
        // reset assertion list
        res.setAssertion(new ArrayList());
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "Assertion encrypted.");
        }
    } else {
        // assertion if applicable
        if (toEncryptNameID) {
            // we need to encrypt the NameID            
            Subject subject = assertion.getSubject();
            if (subject == null) {
                return;
            }
            NameID nameID = subject.getNameID();
            if (nameID == null) {
                return;
            }
            EncryptedID encryptedNameID = nameID.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), spEntityID);
            if (encryptedNameID == null) {
                SAML2Utils.debug.error(classMethod + "failed to encrypt the NameID.");
                throw new SAML2Exception(SAML2Utils.bundle.getString("FailedToEncryptNameID"));
            }
            subject.setEncryptedID(encryptedNameID);
            // reset NameID
            subject.setNameID(null);
            assertion.setSubject(subject);
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "NameID encrypted.");
            }
        }
        if (toEncryptAttribute) {
            // we need to encrypt the Attribute
            List attributeStatements = assertion.getAttributeStatements();
            if ((attributeStatements != null) && (attributeStatements.size() > 0)) {
                int asSize = attributeStatements.size();
                // to hold all the AttributeStatements
                List stmts = new ArrayList();
                for (int i = 0; i < asSize; i++) {
                    AttributeStatement attributeStatement = (AttributeStatement) attributeStatements.get(i);
                    List attributes = attributeStatement.getAttribute();
                    if ((attributes == null) || (attributes.size() == 0)) {
                        continue;
                    }
                    int aSize = attributes.size();
                    // holds all the encrypted Attributes in this statement
                    List eaList = new ArrayList();
                    for (int j = 0; j < aSize; j++) {
                        Attribute attribute = (Attribute) attributes.get(j);
                        EncryptedAttribute encryptedAttribute = attribute.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), spEntityID);
                        if (encryptedAttribute == null) {
                            SAML2Utils.debug.error(classMethod + "failed to encrypt the Attribute.");
                            throw new SAML2Exception(SAML2Utils.bundle.getString("FailedToEncryptAttribute"));
                        }
                        eaList.add(encryptedAttribute);
                    }
                    attributeStatement.setEncryptedAttribute(eaList);
                    attributeStatement.setAttribute(new ArrayList());
                    stmts.add(attributeStatement);
                }
                assertion.setAttributeStatements(stmts);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "Attribute encrypted.");
                }
            }
        }
        if (signAssertion) {
            signAssertion(realm, idpEntityID, assertion);
        }
        List assertionList = new ArrayList();
        assertionList.add(assertion);
        res.setAssertion(assertionList);
    }
}
Also used : EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) NameID(com.sun.identity.saml2.assertion.NameID) Attribute(com.sun.identity.saml2.assertion.Attribute) EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) ArrayList(java.util.ArrayList) EncryptedID(com.sun.identity.saml2.assertion.EncryptedID) Subject(com.sun.identity.saml2.assertion.Subject) EncInfo(com.sun.identity.saml2.key.EncInfo) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement) List(java.util.List) ArrayList(java.util.ArrayList)

Example 25 with NameID

use of com.sun.identity.saml2.assertion.NameID in project OpenAM by OpenRock.

the class IDPProxyUtil method getNameIDFormat.

private static String getNameIDFormat(Response res) {
    if (res == null) {
        return null;
    }
    List assertions = res.getAssertion();
    if ((assertions == null) || (assertions.size() == 0)) {
        return null;
    }
    Assertion assertion = (Assertion) assertions.get(0);
    Subject subject = assertion.getSubject();
    if (subject == null) {
        return null;
    }
    NameID nameID = subject.getNameID();
    if (nameID == null) {
        return null;
    }
    String format = nameID.getFormat();
    return format;
}
Also used : NameID(com.sun.identity.saml2.assertion.NameID) Assertion(com.sun.identity.saml2.assertion.Assertion) List(java.util.List) IDPList(com.sun.identity.saml2.protocol.IDPList) ArrayList(java.util.ArrayList) Subject(com.sun.identity.saml2.assertion.Subject)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)46 NameID (com.sun.identity.saml2.assertion.NameID)33 List (java.util.List)25 ArrayList (java.util.ArrayList)22 EncryptedID (com.sun.identity.saml2.assertion.EncryptedID)18 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)15 HashMap (java.util.HashMap)14 SessionException (com.sun.identity.plugin.session.SessionException)12 NameIDInfo (com.sun.identity.saml2.common.NameIDInfo)12 Map (java.util.Map)11 Subject (com.sun.identity.saml2.assertion.Subject)10 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)10 Element (org.w3c.dom.Element)10 Date (java.util.Date)9 Iterator (java.util.Iterator)9 AssertionFactory (com.sun.identity.saml2.assertion.AssertionFactory)8 SAML2MetaManager (com.sun.identity.saml2.meta.SAML2MetaManager)8 Assertion (com.sun.identity.saml2.assertion.Assertion)7 Issuer (com.sun.identity.saml2.assertion.Issuer)7 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)7