Search in sources :

Example 1 with AuthnStatement

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

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

the class SAML2Utils method fillMap.

private static Map fillMap(final List authnStmts, final Subject subject, final Assertion assertion, final List assertions, final AuthnRequestInfo reqInfo, final String inRespToResp, final String orgName, final String hostEntityId, final String idpEntityId, final SPSSOConfigElement spConfig, final Date notOnOrAfterTime) throws SAML2Exception {
    // use the first AuthnStmt
    AuthnStatement authnStmt = (AuthnStatement) authnStmts.get(0);
    int authLevel = -1;
    String mapperClass = getAttributeValueFromSPSSOConfig(spConfig, SAML2Constants.SP_AUTHCONTEXT_MAPPER);
    SPAuthnContextMapper mapper = getSPAuthnContextMapper(orgName, hostEntityId, mapperClass);
    RequestedAuthnContext reqContext = null;
    AuthnRequest authnRequest = null;
    if (reqInfo != null) {
        reqContext = (reqInfo.getAuthnRequest()).getRequestedAuthnContext();
        authnRequest = reqInfo.getAuthnRequest();
    }
    authLevel = mapper.getAuthLevel(reqContext, authnStmt.getAuthnContext(), orgName, hostEntityId, idpEntityId);
    String sessionIndex = authnStmt.getSessionIndex();
    Date sessionNotOnOrAfter = authnStmt.getSessionNotOnOrAfter();
    Map smap = new HashMap();
    smap.put(SAML2Constants.SUBJECT, subject);
    smap.put(SAML2Constants.POST_ASSERTION, assertion);
    smap.put(SAML2Constants.ASSERTIONS, assertions);
    if (authnRequest != null) {
        smap.put(SAML2Constants.AUTHN_REQUEST, authnRequest);
    }
    String[] data = { assertion.getID(), "", "" };
    if (LogUtil.isAccessLoggable(Level.FINE)) {
        data[1] = subject.toXMLString();
    }
    if (sessionIndex != null && sessionIndex.length() != 0) {
        data[2] = sessionIndex;
        smap.put(SAML2Constants.SESSION_INDEX, sessionIndex);
    }
    if (authLevel >= 0) {
        smap.put(SAML2Constants.AUTH_LEVEL, new Integer(authLevel));
    }
    // SessionNotOnOrAfter
    if (sessionNotOnOrAfter != null) {
        long maxSessionTime = (sessionNotOnOrAfter.getTime() - System.currentTimeMillis()) / 60000;
        if (maxSessionTime > 0) {
            smap.put(SAML2Constants.MAX_SESSION_TIME, new Long(maxSessionTime));
        }
    }
    if (inRespToResp != null && inRespToResp.length() != 0) {
        smap.put(SAML2Constants.IN_RESPONSE_TO, inRespToResp);
    }
    if (debug.messageEnabled()) {
        debug.message("SAML2Utils.fillMap: Found valid authentication " + "assertion.");
    }
    if (notOnOrAfterTime != null) {
        smap.put(SAML2Constants.NOTONORAFTER, new Long(notOnOrAfterTime.getTime()));
    }
    LogUtil.access(Level.INFO, LogUtil.FOUND_AUTHN_ASSERTION, data, null);
    return smap;
}
Also used : HashMap(java.util.HashMap) Date(java.util.Date) RequestedAuthnContext(com.sun.identity.saml2.protocol.RequestedAuthnContext) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) AuthnStatement(com.sun.identity.saml2.assertion.AuthnStatement) SPAuthnContextMapper(com.sun.identity.saml2.plugins.SPAuthnContextMapper) DefaultSPAuthnContextMapper(com.sun.identity.saml2.plugins.DefaultSPAuthnContextMapper) Map(java.util.Map) HashMap(java.util.HashMap)

Example 3 with AuthnStatement

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

the class AssertionGen method getAuthStatementList.

/**
 *Generate auth statements and retun a list of auth statements
 *
 */
private List getAuthStatementList() {
    AuthnStatement authnStatement = AssertionFactory.getInstance().createAuthnStatement();
    AuthnContext authnContext = AssertionFactory.getInstance().createAuthnContext();
    List AuthStatementList = new ArrayList();
    try {
        authnContext.setAuthnContextClassRef(SAML2Constants.CLASSREF_PASSWORD_PROTECTED_TRANSPORT);
        authnStatement.setAuthnContext(authnContext);
        authnStatement.setAuthnInstant(new Date());
        authnStatement.setSessionIndex("session_index");
        AuthStatementList.add(authnStatement);
    } catch (SAML2Exception ex) {
        Logger.getLogger(AssertionGen.class.getName()).log(Level.SEVERE, null, ex);
    }
    return AuthStatementList;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ArrayList(java.util.ArrayList) List(java.util.List) ArrayList(java.util.ArrayList) Date(java.util.Date)

Example 4 with AuthnStatement

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

the class DefaultAuthenticationStatementsProvider method get.

/**
     * @see org.forgerock.openam.sts.tokengeneration.saml2.statements.AttributeStatementsProvider#get(com.iplanet.sso.SSOToken,
     * org.forgerock.openam.sts.config.user.SAML2Config, AttributeMapper)
     */
public List<AuthnStatement> get(SAML2Config saml2Config, String authNContextClassRef) throws TokenCreationException {
    try {
        AuthnStatement authnStatement = AssertionFactory.getInstance().createAuthnStatement();
        authnStatement.setAuthnInstant(new Date());
        AuthnContext authnContext = AssertionFactory.getInstance().createAuthnContext();
        authnContext.setAuthnContextClassRef(authNContextClassRef);
        authnStatement.setAuthnContext(authnContext);
        ArrayList<AuthnStatement> statements = new ArrayList<AuthnStatement>(1);
        statements.add(authnStatement);
        return statements;
    } catch (SAML2Exception e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught generating AuthenticationStatement in DefaultAuthenticationStatementProvider: " + e, e);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AuthnStatement(com.sun.identity.saml2.assertion.AuthnStatement) ArrayList(java.util.ArrayList) TokenCreationException(org.forgerock.openam.sts.TokenCreationException) Date(java.util.Date) AuthnContext(com.sun.identity.saml2.assertion.AuthnContext)

Example 5 with AuthnStatement

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

the class AssertionImpl method toXMLString.

/**
    * Returns a String representation
    * @param includeNSPrefix Determines whether or not the namespace
    *        qualifier is prepended to the Element when converted
    * @param declareNS Determines whether or not the namespace is declared
    *        within the Element.
    * @return A String representation
    * @exception SAML2Exception if something is wrong during conversion
    */
@Override
public String toXMLString(boolean includeNSPrefix, boolean declareNS) throws SAML2Exception {
    if ((signature != null) && (signedXMLString != null)) {
        return signedXMLString;
    }
    StringBuffer sb = new StringBuffer(2000);
    String NS = "";
    String appendNS = "";
    if (declareNS) {
        NS = SAML2Constants.ASSERTION_DECLARE_STR;
    }
    if (includeNSPrefix) {
        appendNS = SAML2Constants.ASSERTION_PREFIX;
    }
    sb.append("<").append(appendNS).append(ASSERTION_ELEMENT).append(NS);
    if ((version == null) || (version.length() == 0)) {
        SAML2SDKUtils.debug.error("AssertionImpl.toXMLString(): version missing");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_assertion_version"));
    }
    sb.append(" ").append(ASSERTION_VERSION_ATTR).append("=\"").append(version).append("\"");
    if ((id == null) || (id.length() == 0)) {
        SAML2SDKUtils.debug.error("AssertionImpl.toXMLString(): assertion id missing");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_assertion_id"));
    }
    sb.append(" ").append(ASSERTION_ID_ATTR).append("=\"").append(id).append("\"");
    if (issueInstant == null) {
        SAML2SDKUtils.debug.error("AssertionImpl.toXMLString(): issue instant missing");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_issue_instant"));
    }
    String instantStr = DateUtils.toUTCDateFormat(issueInstant);
    sb.append(" ").append(ASSERTION_ISSUEINSTANT_ATTR).append("=\"").append(instantStr).append("\"").append(">\n");
    if (issuer == null) {
        SAML2SDKUtils.debug.error("AssertionImpl.toXMLString(): issuer missing");
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("missing_subelement_issuer"));
    }
    sb.append(issuer.toXMLString(includeNSPrefix, false));
    if (signature != null) {
        sb.append(signature);
    }
    if (subject != null) {
        sb.append(subject.toXMLString(includeNSPrefix, false));
    }
    if (conditions != null) {
        sb.append(conditions.toXMLString(includeNSPrefix, false));
    }
    if (advice != null) {
        sb.append(advice.toXMLString(includeNSPrefix, false));
    }
    int length = 0;
    if (statements != null) {
        length = statements.size();
        for (int i = 0; i < length; i++) {
            String str = (String) statements.get(i);
            sb.append(str);
        }
    }
    if (authnStatements != null) {
        length = authnStatements.size();
        for (int i = 0; i < length; i++) {
            AuthnStatement st = (AuthnStatement) authnStatements.get(i);
            sb.append(st.toXMLString(includeNSPrefix, false));
        }
    }
    if (authzDecisionStatements != null) {
        length = authzDecisionStatements.size();
        for (int i = 0; i < length; i++) {
            AuthzDecisionStatement st = (AuthzDecisionStatement) authzDecisionStatements.get(i);
            sb.append(st.toXMLString(includeNSPrefix, false));
        }
    }
    if (attributeStatements != null) {
        length = attributeStatements.size();
        for (int i = 0; i < length; i++) {
            AttributeStatement st = (AttributeStatement) attributeStatements.get(i);
            sb.append(st.toXMLString(includeNSPrefix, false));
        }
    }
    sb.append("</").append(appendNS).append(ASSERTION_ELEMENT).append(">\n");
    //return SAML2Utils.removeNewLineChars(sb.toString());
    return sb.toString();
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement) AuthzDecisionStatement(com.sun.identity.saml2.assertion.AuthzDecisionStatement) AuthnStatement(com.sun.identity.saml2.assertion.AuthnStatement)

Aggregations

AuthnStatement (com.sun.identity.saml2.assertion.AuthnStatement)8 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)7 Date (java.util.Date)6 ArrayList (java.util.ArrayList)5 Assertion (com.sun.identity.saml2.assertion.Assertion)3 AttributeStatement (com.sun.identity.saml2.assertion.AttributeStatement)3 AuthnContext (com.sun.identity.saml2.assertion.AuthnContext)3 EncryptedAssertion (com.sun.identity.saml2.assertion.EncryptedAssertion)3 List (java.util.List)3 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)3 SessionException (com.sun.identity.plugin.session.SessionException)2 AuthzDecisionStatement (com.sun.identity.saml2.assertion.AuthzDecisionStatement)2 Issuer (com.sun.identity.saml2.assertion.Issuer)2 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)2 IDPAuthnContextMapper (com.sun.identity.saml2.plugins.IDPAuthnContextMapper)2 RequestedAuthnContext (com.sun.identity.saml2.protocol.RequestedAuthnContext)2 Response (com.sun.identity.saml2.protocol.Response)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 COTException (com.sun.identity.cot.COTException)1 AssertionFactory (com.sun.identity.saml2.assertion.AssertionFactory)1