Search in sources :

Example 1 with NewBoolean

use of com.sun.identity.saml2.common.NewBoolean 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 2 with NewBoolean

use of com.sun.identity.saml2.common.NewBoolean in project OpenAM by OpenRock.

the class IDPSSOUtil method getAuthnStatement.

/**
     * Returns a <code>SAML AuthnStatement</code> object.
     *
     * @param request The HTTP request.
     * @param session The user's session.
     * @param isNewSessionIndex A returned flag from which the caller knows if the session index in the returned
     *                          <code>AuthnStatement</code> is a new session index.
     * @param authnReq The <code>AuthnRequest</code> object.
     * @param idpEntityID The entity ID of the identity provider.
     * @param realm The realm name.
     * @param matchingAuthnContext The <code>AuthnContext</code> used to find authentication type and scheme.
     * @return The <code>SAML AuthnStatement</code> object.
     * @throws SAML2Exception If the operation is not successful.
     */
private static AuthnStatement getAuthnStatement(HttpServletRequest request, Object session, NewBoolean isNewSessionIndex, AuthnRequest authnReq, String idpEntityID, String realm, AuthnContext matchingAuthnContext) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.getAuthnStatement: ";
    AuthnStatement authnStatement = AssertionFactory.getInstance().createAuthnStatement();
    Date authInstant = null;
    // will be used when we add SubjectLocality to the statement
    try {
        String[] values = sessionProvider.getProperty(session, SessionProvider.AUTH_INSTANT);
        if (values != null && values.length != 0 && values[0] != null && values[0].length() != 0) {
            authInstant = DateUtils.stringToDate(values[0]);
        }
    } catch (Exception e) {
        SAML2Utils.debug.error(classMethod + "exception retrieving info from the session: ", e);
        throw new SAML2Exception(SAML2Utils.bundle.getString("errorGettingAuthnStatement"));
    }
    if (authInstant == null) {
        authInstant = new Date();
    }
    authnStatement.setAuthnInstant(authInstant);
    AuthnContext authnContext = matchingAuthnContext;
    if (authnContext == null) {
        String authLevel = null;
        try {
            String[] values = sessionProvider.getProperty(session, SessionProvider.AUTH_LEVEL);
            if (values != null && values.length != 0 && values[0] != null && values[0].length() != 0) {
                authLevel = values[0];
            }
        } catch (Exception e) {
            SAML2Utils.debug.error(classMethod + "exception retrieving auth level info from the session: ", e);
            throw new SAML2Exception(SAML2Utils.bundle.getString("errorGettingAuthnStatement"));
        }
        IDPAuthnContextMapper idpAuthnContextMapper = getIDPAuthnContextMapper(realm, idpEntityID);
        authnContext = idpAuthnContextMapper.getAuthnContextFromAuthLevel(authLevel, realm, idpEntityID);
    }
    final Response idpResponse = (Response) request.getAttribute(SAML2Constants.SAML_PROXY_IDP_RESPONSE_KEY);
    if (idpResponse != null) {
        // IdP proxy case: we already received an assertion from the remote IdP and now the IdP proxy is generating
        // a new SAML response for the SP.
        Set<String> authenticatingAuthorities = new LinkedHashSet<String>();
        final List<Assertion> assertions = idpResponse.getAssertion();
        for (Assertion assertion : assertions) {
            authenticatingAuthorities.addAll(extractAuthenticatingAuthorities(assertion));
        }
        // According to SAML profile 4.1.4.2 each assertion within the SAML Response MUST have the same issuer, so
        // this should suffice. We should have at least one assertion, since the IdP proxy's SP already accepted it.
        authenticatingAuthorities.add(assertions.iterator().next().getIssuer().getValue());
        authnContext.setAuthenticatingAuthority(new ArrayList<String>(authenticatingAuthorities));
    }
    authnStatement.setAuthnContext(authnContext);
    String sessionIndex = getSessionIndex(session);
    if (sessionIndex == null) {
        // new sessionIndex
        sessionIndex = SAML2Utils.generateIDWithServerID();
        try {
            String[] values = { sessionIndex };
            sessionProvider.setProperty(session, SAML2Constants.IDP_SESSION_INDEX, values);
        } catch (SessionException e) {
            SAML2Utils.debug.error(classMethod + "error setting session index into the session: ", e);
            throw new SAML2Exception(SAML2Utils.bundle.getString("errorGettingAuthnStatement"));
        }
        isNewSessionIndex.setValue(true);
    } else {
        isNewSessionIndex.setValue(false);
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "SessionIndex (in AuthnStatement) =" + sessionIndex);
    }
    if (sessionIndex != null) {
        Set authContextSet = (HashSet) IDPCache.authnContextCache.get(sessionIndex);
        if (authContextSet == null || authContextSet.isEmpty()) {
            authContextSet = new HashSet();
        }
        authContextSet.add(authnContext);
        // cache the AuthContext to use in the case of session upgrade.
        IDPCache.authnContextCache.put(sessionIndex, authContextSet);
        authnStatement.setSessionIndex(sessionIndex);
    }
    return authnStatement;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) IDPAuthnContextMapper(com.sun.identity.saml2.plugins.IDPAuthnContextMapper) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) SessionException(com.sun.identity.plugin.session.SessionException) Date(java.util.Date) SAML2InvalidNameIDPolicyException(com.sun.identity.saml2.common.SAML2InvalidNameIDPolicyException) SessionException(com.sun.identity.plugin.session.SessionException) COTException(com.sun.identity.cot.COTException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AuthnContext(com.sun.identity.saml2.assertion.AuthnContext) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ECPResponse(com.sun.identity.saml2.ecp.ECPResponse) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthnStatement(com.sun.identity.saml2.assertion.AuthnStatement) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

SessionException (com.sun.identity.plugin.session.SessionException)2 Assertion (com.sun.identity.saml2.assertion.Assertion)2 AuthnStatement (com.sun.identity.saml2.assertion.AuthnStatement)2 EncryptedAssertion (com.sun.identity.saml2.assertion.EncryptedAssertion)2 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)2 Date (java.util.Date)2 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)2 COTException (com.sun.identity.cot.COTException)1 AttributeStatement (com.sun.identity.saml2.assertion.AttributeStatement)1 AuthnContext (com.sun.identity.saml2.assertion.AuthnContext)1 Conditions (com.sun.identity.saml2.assertion.Conditions)1 Issuer (com.sun.identity.saml2.assertion.Issuer)1 Subject (com.sun.identity.saml2.assertion.Subject)1 NewBoolean (com.sun.identity.saml2.common.NewBoolean)1 SAML2InvalidNameIDPolicyException (com.sun.identity.saml2.common.SAML2InvalidNameIDPolicyException)1 ECPResponse (com.sun.identity.saml2.ecp.ECPResponse)1 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)1 IDPAuthnContextMapper (com.sun.identity.saml2.plugins.IDPAuthnContextMapper)1 Response (com.sun.identity.saml2.protocol.Response)1 IOException (java.io.IOException)1