Search in sources :

Example 1 with AttributeStatement

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

the class SPACSUtils method getSAMLAttributes.

/**
     * Gets the attributes from an assert's AttributeStates.
     *
     * @param assertion The assertion from which to pull the AttributeStates.
     * @param needAttributeEncrypted Whether attributes must be encrypted (or else rejected).
     * @param privateKeys Private keys used to decrypt those encrypted attributes.
     * @return a list of attributes pulled from the provided assertion.
     */
public static List<Attribute> getSAMLAttributes(Assertion assertion, boolean needAttributeEncrypted, Set<PrivateKey> privateKeys) {
    List<Attribute> attrList = null;
    if (assertion != null) {
        List<AttributeStatement> statements = assertion.getAttributeStatements();
        if (CollectionUtils.isNotEmpty(statements)) {
            for (AttributeStatement statement : statements) {
                List<Attribute> attributes = statement.getAttribute();
                if (needAttributeEncrypted && attributes != null && !attributes.isEmpty()) {
                    SAML2Utils.debug.error("Attribute not encrypted.");
                    return null;
                }
                if (attributes != null) {
                    if (attrList == null) {
                        attrList = new ArrayList<>();
                    }
                    attrList.addAll(attributes);
                }
                List<EncryptedAttribute> encAttrs = statement.getEncryptedAttribute();
                if (encAttrs != null) {
                    for (EncryptedAttribute encAttr : encAttrs) {
                        if (attrList == null) {
                            attrList = new ArrayList<>();
                        }
                        try {
                            attrList.add((encAttr).decrypt(privateKeys));
                        } catch (SAML2Exception se) {
                            SAML2Utils.debug.error("Decryption error:", se);
                            return null;
                        }
                    }
                }
            }
        }
    }
    return attrList;
}
Also used : EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Attribute(com.sun.identity.saml2.assertion.Attribute) EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement)

Example 2 with AttributeStatement

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

the class DefaultLibrarySPAccountMapper method getAutoFedUser.

/**
     * Returns user for the auto federate attribute.
     *
     * @param realm Realm name.
     * @param entityID Hosted <code>EntityID</code>.
     * @param assertion <code>Assertion</code> from the identity provider.
     * @return Auto federation mapped user from the assertion auto federation <code>AttributeStatement</code>. if the
     * statement does not have the auto federation attribute then the NameID value will be used if use NameID as SP user
     * ID is enabled, otherwise null.
     */
protected String getAutoFedUser(String realm, String entityID, Assertion assertion, String decryptedNameID, Set<PrivateKey> decryptionKeys) throws SAML2Exception {
    if (!isAutoFedEnabled(realm, entityID)) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation is disabled.");
        }
        return null;
    }
    String autoFedAttribute = getAttribute(realm, entityID, SAML2Constants.AUTO_FED_ATTRIBUTE);
    if (autoFedAttribute == null || autoFedAttribute.isEmpty()) {
        debug.error("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Auto federation is enabled but the auto federation attribute is not configured.");
        return null;
    }
    if (debug.messageEnabled()) {
        debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation attribute is set to: " + autoFedAttribute);
    }
    Set<String> autoFedAttributeValue = null;
    List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Assertion does not have any attribute statements.");
        }
    } else {
        for (AttributeStatement statement : attributeStatements) {
            autoFedAttributeValue = getAttribute(statement, autoFedAttribute, decryptionKeys);
            if (autoFedAttributeValue != null && !autoFedAttributeValue.isEmpty()) {
                if (debug.messageEnabled()) {
                    debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Found auto federation attribute value in Assertion: " + autoFedAttributeValue);
                }
                break;
            }
        }
    }
    if (autoFedAttributeValue == null || autoFedAttributeValue.isEmpty()) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Auto federation attribute is not specified" + " as an attribute.");
        }
        if (!useNameIDAsSPUserID(realm, entityID)) {
            if (debug.messageEnabled()) {
                debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: NameID as SP UserID was not enabled " + " and auto federation attribute " + autoFedAttribute + " was not found in the Assertion");
            }
            return null;
        } else {
            if (debug.messageEnabled()) {
                debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Trying now to autofederate with nameID" + ", nameID =" + decryptedNameID);
            }
            autoFedAttributeValue = CollectionUtils.asSet(decryptedNameID);
        }
    }
    String autoFedMapAttribute = null;
    DefaultSPAttributeMapper attributeMapper = new DefaultSPAttributeMapper();
    Map<String, String> attributeMap = attributeMapper.getConfigAttributeMap(realm, entityID, SP);
    if (attributeMap == null || attributeMap.isEmpty()) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: attribute map is not configured.");
        }
    } else {
        autoFedMapAttribute = attributeMap.get(autoFedAttribute);
    }
    if (autoFedMapAttribute == null) {
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: " + "Auto federation attribute map is not specified in config.");
        }
        // assume it is the same as the auto fed attribute name 
        autoFedMapAttribute = autoFedAttribute;
    }
    try {
        Map<String, Set<String>> map = new HashMap<>(1);
        map.put(autoFedMapAttribute, autoFedAttributeValue);
        if (debug.messageEnabled()) {
            debug.message("DefaultLibrarySPAccountMapper.getAutoFedUser: Search map: " + map);
        }
        String userId = dsProvider.getUserID(realm, map);
        if (userId != null && !userId.isEmpty()) {
            return userId;
        } else {
            // return auto-federation attribute value as uid 
            if (isDynamicalOrIgnoredProfile(realm)) {
                if (debug.messageEnabled()) {
                    debug.message("DefaultLibrarySPAccountMapper: dynamical user creation or ignore profile " + "enabled : uid=" + autoFedAttributeValue);
                }
                // return the first value as uid
                return autoFedAttributeValue.iterator().next();
            }
        }
    } catch (DataStoreProviderException dse) {
        if (debug.warningEnabled()) {
            debug.warning("DefaultLibrarySPAccountMapper.getAutoFedUser: Datastore provider exception", dse);
        }
    }
    return null;
}
Also used : DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement)

Example 3 with AttributeStatement

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

the class DefaultLibrarySPAccountMapper method getAttribute.

private Set<String> getAttribute(AttributeStatement statement, String attributeName, Set<PrivateKey> decryptionKeys) {
    if (debug.messageEnabled()) {
        debug.message("DefaultLibrarySPAccountMapper.getAttribute: attribute Name =" + attributeName);
    }
    // check it if the attribute needs to be encrypted?
    List<Attribute> list = statement.getAttribute();
    List<EncryptedAttribute> encList = statement.getEncryptedAttribute();
    if (encList != null && !encList.isEmpty()) {
        // a new list to hold the union of clear and encrypted attributes
        List<Attribute> allList = new ArrayList<>();
        if (list != null) {
            allList.addAll(list);
        }
        list = allList;
        for (EncryptedAttribute encryptedAttribute : encList) {
            try {
                list.add(encryptedAttribute.decrypt(decryptionKeys));
            } catch (SAML2Exception se) {
                debug.error("Decryption error:", se);
                return null;
            }
        }
    }
    for (Attribute attribute : list) {
        if (!attributeName.equalsIgnoreCase(attribute.getName())) {
            continue;
        }
        List<String> values = attribute.getAttributeValueString();
        if (values == null || values.isEmpty()) {
            return null;
        }
        return new HashSet<>(values);
    }
    return null;
}
Also used : EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Attribute(com.sun.identity.saml2.assertion.Attribute) EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet)

Example 4 with AttributeStatement

use of com.sun.identity.saml2.assertion.AttributeStatement 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 5 with AttributeStatement

use of com.sun.identity.saml2.assertion.AttributeStatement 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)

Aggregations

AttributeStatement (com.sun.identity.saml2.assertion.AttributeStatement)12 Attribute (com.sun.identity.saml2.assertion.Attribute)8 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)8 ArrayList (java.util.ArrayList)8 EncryptedAttribute (com.sun.identity.saml2.assertion.EncryptedAttribute)5 Assertion (com.sun.identity.saml2.assertion.Assertion)4 EncryptedAssertion (com.sun.identity.saml2.assertion.EncryptedAssertion)4 Subject (com.sun.identity.saml2.assertion.Subject)4 List (java.util.List)4 AuthnStatement (com.sun.identity.saml2.assertion.AuthnStatement)3 Conditions (com.sun.identity.saml2.assertion.Conditions)3 Issuer (com.sun.identity.saml2.assertion.Issuer)3 Date (java.util.Date)3 HashSet (java.util.HashSet)3 AuthzDecisionStatement (com.sun.identity.saml2.assertion.AuthzDecisionStatement)2 HashMap (java.util.HashMap)2 Set (java.util.Set)2 TokenCreationException (org.forgerock.openam.sts.TokenCreationException)2 DataStoreProviderException (com.sun.identity.plugin.datastore.DataStoreProviderException)1 SessionException (com.sun.identity.plugin.session.SessionException)1