Search in sources :

Example 21 with SAML2TokenRepositoryException

use of org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException in project OpenAM by OpenRock.

the class IDPSingleLogout method processLogoutResponse.

static boolean processLogoutResponse(HttpServletRequest request, HttpServletResponse response, LogoutResponse logoutRes, String relayState, String metaAlias, String idpEntityID, String spEntityID, String realm, String binding) throws SAML2Exception, SessionException {
    // use the cache to figure out which session index is in question
    // and then use the cache to see if any more SPs to send logout request
    // if yes, send one
    // if no, do local logout and send response back to original requesting
    // SP (this SP name should be remembered in cache)
    Object session = sessionProvider.getSession(request);
    String tokenID = sessionProvider.getSessionID(session);
    String idpSessionIndex = IDPSSOUtil.getSessionIndex(session);
    if (idpSessionIndex == null) {
        if (debug.messageEnabled()) {
            debug.message("No SP session participant(s)");
        }
        MultiProtocolUtils.invalidateSession(session, request, response, SingleLogoutManager.SAML2);
        return false;
    }
    IDPSession idpSession = IDPCache.idpSessionsByIndices.get(idpSessionIndex);
    if (idpSession == null) {
        if (debug.messageEnabled()) {
            debug.message("IDPSLO.processLogoutResponse : " + "IDP Session with session index " + idpSessionIndex + " already removed.");
        }
        try {
            if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                SAML2FailoverUtils.deleteSAML2Token(idpSessionIndex);
            }
        } catch (SAML2TokenRepositoryException se) {
            debug.error("IDPSingleLogout.processLogoutRequest: Error while deleting token from " + "SAML2 Token Repository for idpSessionIndex:" + idpSessionIndex, se);
        }
        IDPCache.authnContextCache.remove(idpSessionIndex);
        MultiProtocolUtils.invalidateSession(session, request, response, SingleLogoutManager.SAML2);
        return false;
    }
    if (debug.messageEnabled()) {
        debug.message("idpSessionIndex=" + idpSessionIndex);
    }
    List<NameIDandSPpair> list = idpSession.getNameIDandSPpairs();
    debug.message("idpSession.getNameIDandSPpairs()=" + list);
    if (list.isEmpty()) {
        return sendLastResponse(idpSession, logoutRes, request, response, idpSessionIndex, session, realm, idpEntityID, relayState);
    } else {
        // send Next Requests
        Iterator<NameIDandSPpair> it = list.iterator();
        while (it.hasNext()) {
            NameIDandSPpair pair = it.next();
            it.remove();
            spEntityID = pair.getSPEntityID();
            removeTransientNameIDFromCache(pair.getNameID());
            Map paramsMap = new HashMap(request.getParameterMap());
            paramsMap.put(SAML2Constants.ROLE, SAML2Constants.IDP_ROLE);
            List<SingleLogoutServiceElement> slosList = getSPSLOServiceEndpoints(realm, spEntityID);
            List extensionsList = LogoutUtil.getExtensionsList(request.getParameterMap());
            SPSSOConfigElement spConfig = sm.getSPSSOConfig(realm, spEntityID);
            //When processing a logout response we must ensure that we try to use the original logout request
            //binding to make sure asynchronous bindings have precedence over synchronous bindings.
            SingleLogoutServiceElement logoutEndpoint = LogoutUtil.getMostAppropriateSLOServiceLocation(slosList, idpSession.getOriginatingLogoutRequestBinding());
            if (logoutEndpoint == null) {
                continue;
            }
            StringBuffer requestID = LogoutUtil.doLogout(metaAlias, spEntityID, extensionsList, logoutEndpoint, relayState, idpSessionIndex, pair.getNameID(), request, response, paramsMap, spConfig);
            String bindingUsed = logoutEndpoint.getBinding();
            if (bindingUsed.equals(SAML2Constants.HTTP_REDIRECT) || bindingUsed.equals(SAML2Constants.HTTP_POST)) {
                String requestIDStr = requestID.toString();
                if (debug.messageEnabled()) {
                    debug.message("IDPSingleLogout.processLogoutRequest: requestIDStr = " + requestIDStr + "\nbinding = " + bindingUsed);
                }
                if (requestIDStr != null && requestIDStr.length() != 0) {
                    idpSession.setPendingLogoutRequestID(requestIDStr);
                }
                return true;
            }
        }
        //response.
        return sendLastResponse(idpSession, logoutRes, request, response, idpSessionIndex, session, realm, idpEntityID, relayState);
    }
}
Also used : HashMap(java.util.HashMap) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) SingleLogoutServiceElement(com.sun.identity.saml2.jaxb.metadata.SingleLogoutServiceElement) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map)

Example 22 with SAML2TokenRepositoryException

use of org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException in project OpenAM by OpenRock.

the class IDPSessionListener method sessionInvalidated.

/**
     *  Callback for SessionListener.
     *  It is used for cleaning up the IDP session cache.
     *  
     *  @param session The session object
     */
public void sessionInvalidated(Object session) {
    String classMethod = "IDPSessionListener.sessionInvalidated: ";
    HashMap paramsMap = new HashMap();
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "Entering ...");
    }
    if (session == null) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "Session is null.");
        }
        return;
    }
    try {
        SessionProvider sessionProvider = SessionManager.getProvider();
        String[] values = sessionProvider.getProperty(session, SAML2Constants.IDP_SESSION_INDEX);
        if (values == null || values.length == 0) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "No sessionIndex stored in session.");
            }
            return;
        }
        String sessionIndex = values[0];
        if (sessionIndex == null || sessionIndex.length() == 0) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "No sessionIndex stored in session.");
            }
            return;
        }
        IDPSession idpSession = (IDPSession) IDPCache.idpSessionsByIndices.get(sessionIndex);
        if (idpSession != null) {
            paramsMap.put(SAML2Constants.ROLE, SAML2Constants.IDP_ROLE);
            String metaAlias = idpSession.getMetaAlias();
            String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
            String idpEntityID = sm.getEntityByMetaAlias(metaAlias);
            try {
                List list = (List) idpSession.getNameIDandSPpairs();
                for (Iterator iter = list.iterator(); iter.hasNext(); ) {
                    NameIDandSPpair pair = (NameIDandSPpair) iter.next();
                    String spEntityID = pair.getSPEntityID();
                    NameID nameID = pair.getNameID();
                    BaseConfigType idpConfig = sm.getIDPSSOConfig(realm, idpEntityID);
                    if (idpConfig != null) {
                        List idpSessionSyncList = (List) SAML2MetaUtils.getAttributes(idpConfig).get(SAML2Constants.IDP_SESSION_SYNC_ENABLED);
                        if ((idpEntityID != null && spEntityID != null && idpSessionSyncList != null && idpSessionSyncList.size() != 0)) {
                            boolean idpSessionSyncEnabled = ((String) idpSessionSyncList.get(0)).equals(SAML2Constants.TRUE) ? true : false;
                            // Sync flag is enabled
                            if (idpSessionSyncEnabled) {
                                if (SAML2Utils.debug.messageEnabled()) {
                                    SAML2Utils.debug.message(classMethod + "IDP Session Synchronization flag " + "is enabled, initiating SLO to SP");
                                }
                                initiateIDPSingleLogout(sessionIndex, metaAlias, realm, SAML2Constants.SOAP, nameID, spEntityID, paramsMap);
                            }
                        }
                    } else {
                        if (SAML2Utils.debug.messageEnabled()) {
                            SAML2Utils.debug.message(classMethod + "Unable to retrieve the IDP " + "config data, idpConfig is null");
                        }
                    }
                }
            } catch (SAML2MetaException sme) {
                SAML2Utils.debug.error("IDPSessionListener.sessionInvalidated:", sme);
            } catch (SAML2Exception se) {
                SAML2Utils.debug.error("IDPSessionListener.sessionInvalidated:", se);
            } catch (SessionException s) {
                SAML2Utils.debug.error("IDPSessionListener.sessionInvalidated:", s);
            }
            synchronized (IDPCache.idpSessionsByIndices) {
                List list = (List) idpSession.getNameIDandSPpairs();
                for (Iterator iter = list.iterator(); iter.hasNext(); ) {
                    NameIDandSPpair pair = (NameIDandSPpair) iter.next();
                    NameID nameID = pair.getNameID();
                    if (SAML2Constants.NAMEID_TRANSIENT_FORMAT.equals(nameID.getFormat())) {
                        IDPCache.userIDByTransientNameIDValue.remove(nameID.getValue());
                    }
                }
            }
        } else {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "IDP Session with session index " + sessionIndex + " already removed.");
            }
        }
        IDPCache.idpSessionsByIndices.remove(sessionIndex);
        IDPCache.authnContextCache.remove(sessionIndex);
        String sessID = sessionProvider.getSessionID(session);
        if (IDPCache.idpSessionsBySessionID.get(sessID) != null) {
            IDPCache.idpSessionsBySessionID.remove(sessID);
            if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                saml2Svc.setIdpSessionCount((long) IDPCache.idpSessionsBySessionID.size());
            }
        }
        if (IDPCache.spSessionPartnerBySessionID.get(sessID) != null) {
            IDPCache.spSessionPartnerBySessionID.remove(sessID);
        }
        // This failing should not cause the whole process to fail
        try {
            if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                SAML2FailoverUtils.deleteSAML2Token(sessionIndex);
            }
        } catch (SAML2TokenRepositoryException se) {
            SAML2Utils.debug.error(classMethod + "SAML2 Token Repository error, sessionIndex:" + sessionIndex, se);
        }
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "cleaned up the IDP session cache for a session expiring or being destroyed: sessionIndex=" + sessionIndex);
        }
    } catch (SessionException e) {
        if (SAML2Utils.debug.warningEnabled()) {
            SAML2Utils.debug.warning(classMethod + "invalid or expired session.", e);
        }
    } catch (SAML2MetaException samlme) {
        if (SAML2Utils.debug.warningEnabled()) {
            SAML2Utils.debug.warning(classMethod + "unable to retrieve idp entity id.", samlme);
        }
    }
}
Also used : HashMap(java.util.HashMap) NameID(com.sun.identity.saml2.assertion.NameID) SessionException(com.sun.identity.plugin.session.SessionException) BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Iterator(java.util.Iterator) List(java.util.List) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Example 23 with SAML2TokenRepositoryException

use of org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException in project OpenAM by OpenRock.

the class Saml2SessionUpgradeHandler method handleSessionUpgrade.

@Override
public void handleSessionUpgrade(InternalSession oldSession, InternalSession newSession) {
    final String sessionIndex = oldSession.getProperty(SAML2Constants.IDP_SESSION_INDEX);
    if (StringUtils.isNotEmpty(sessionIndex)) {
        final String oldSessionID = oldSession.getID().toString();
        final String newSessionID = newSession.getID().toString();
        final SSOToken oldSSOToken;
        final SSOToken newSSOToken;
        try {
            oldSSOToken = ssoTokenManager.createSSOToken(oldSessionID);
            newSSOToken = ssoTokenManager.createSSOToken(newSessionID);
        } catch (SSOException ssoe) {
            debug.warning("Unable to create an SSOToken for the session ID due to " + ssoe.toString());
            return;
        }
        IDPSession idpSession = IDPCache.idpSessionsByIndices.get(sessionIndex);
        if (idpSession == null) {
            if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                try {
                    final IDPSessionCopy idpSessionCopy = (IDPSessionCopy) SAML2FailoverUtils.retrieveSAML2Token(sessionIndex);
                    if (idpSessionCopy != null) {
                        idpSession = new IDPSession(idpSessionCopy);
                    }
                } catch (SAML2TokenRepositoryException stre) {
                    debug.warning("Unable to retrieve IDPSessionCopy from SAML failover store", stre);
                }
            }
        }
        if (idpSession != null) {
            idpSession.setSession(newSSOToken);
            if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
                try {
                    SAML2FailoverUtils.deleteSAML2Token(sessionIndex);
                    long expirationTime = System.currentTimeMillis() / 1000 + newSession.getTimeLeft();
                    SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(sessionIndex, new IDPSessionCopy(idpSession), expirationTime);
                } catch (SAML2TokenRepositoryException stre) {
                    debug.error("Failed to update IDPSession in SAML failover store", stre);
                }
            }
            IDPCache.idpSessionsByIndices.put(sessionIndex, idpSession);
            IDPCache.idpSessionsBySessionID.put(newSessionID, idpSession);
        }
        IDPCache.idpSessionsBySessionID.remove(oldSessionID);
        final String partner = IDPCache.spSessionPartnerBySessionID.remove(oldSessionID);
        if (partner != null) {
            IDPCache.spSessionPartnerBySessionID.put(newSessionID, partner);
        }
        try {
            //We set the sessionIndex to a dummy value so that IDPSessionListener won't try to clear out the caches
            //for the still valid sessionIndex.
            oldSSOToken.setProperty(SAML2Constants.IDP_SESSION_INDEX, "dummy");
        } catch (SSOException ssoe) {
            debug.error("Failed to set IDP Session Index for old session", ssoe);
        }
    }
}
Also used : SSOToken(com.iplanet.sso.SSOToken) IDPSession(com.sun.identity.saml2.profile.IDPSession) SSOException(com.iplanet.sso.SSOException) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) IDPSessionCopy(com.sun.identity.saml2.profile.IDPSessionCopy)

Example 24 with SAML2TokenRepositoryException

use of org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException in project OpenAM by OpenRock.

the class AuthnQueryUtil method processAuthnQuery.

/**
     * This method processes the <code>AuthnQuery</code> coming
     * from a requester.
     *
     * @param authnQuery the <code>AuthnQuery</code> object
     * @param request the <code>HttpServletRequest</code> object
     * @param response the <code>HttpServletResponse</code> object
     * @param authnAuthorityEntityID entity ID of authentication authority
     * @param realm the realm of hosted entity
     *
     * @return the <code>Response</code> object
     * @exception SAML2Exception if the operation is not successful
     */
public static Response processAuthnQuery(AuthnQuery authnQuery, HttpServletRequest request, HttpServletResponse response, String authnAuthorityEntityID, String realm) throws SAML2Exception {
    try {
        verifyAuthnQuery(authnQuery, authnAuthorityEntityID, realm);
    } catch (SAML2Exception se) {
        SAML2Utils.debug.error("AuthnQueryUtil.processAuthnQuery:", se);
        return SAML2Utils.getErrorResponse(authnQuery, SAML2Constants.REQUESTER, null, se.getMessage(), null);
    }
    Issuer issuer = authnQuery.getIssuer();
    String spEntityID = issuer.getValue();
    AuthnAuthorityDescriptorElement aad = null;
    SAML2MetaManager metaManager = SAML2Utils.getSAML2MetaManager();
    try {
        aad = metaManager.getAuthnAuthorityDescriptor(realm, authnAuthorityEntityID);
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error("AuthnQueryUtil.processAuthnQuery:", sme);
        return SAML2Utils.getErrorResponse(authnQuery, SAML2Constants.RESPONDER, null, SAML2Utils.bundle.getString("metaDataError"), null);
    }
    if (aad == null) {
        return SAML2Utils.getErrorResponse(authnQuery, SAML2Constants.REQUESTER, null, SAML2Utils.bundle.getString("authnAuthorityNotFound"), null);
    }
    NameID nameID = getNameID(authnQuery.getSubject(), realm, authnAuthorityEntityID);
    if (nameID == null) {
        return SAML2Utils.getErrorResponse(authnQuery, SAML2Constants.REQUESTER, SAML2Constants.UNKNOWN_PRINCIPAL, null, null);
    }
    IDPAccountMapper idpAcctMapper = SAML2Utils.getIDPAccountMapper(realm, authnAuthorityEntityID);
    String userID = idpAcctMapper.getIdentity(nameID, authnAuthorityEntityID, spEntityID, realm);
    if (userID == null) {
        return SAML2Utils.getErrorResponse(authnQuery, SAML2Constants.REQUESTER, SAML2Constants.UNKNOWN_PRINCIPAL, null, null);
    }
    IDPAuthnContextMapper idpAuthnContextMapper = IDPSSOUtil.getIDPAuthnContextMapper(realm, authnAuthorityEntityID);
    // get assertion for matching authncontext using session
    List returnAssertions = new ArrayList();
    String qSessionIndex = authnQuery.getSessionIndex();
    RequestedAuthnContext requestedAC = authnQuery.getRequestedAuthnContext();
    List assertions = null;
    String cacheKey = userID.toLowerCase();
    AssertionFactory assertionFactory = AssertionFactory.getInstance();
    if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("AuthnQueryUtil.processAuthnQuery: " + "getting user assertions from DB. user = " + cacheKey);
        }
        List list = null;
        try {
            list = SAML2FailoverUtils.retrieveSAML2TokensWithSecondaryKey(cacheKey);
        } catch (SAML2TokenRepositoryException se) {
            SAML2Utils.debug.error("AuthnQueryUtil.processAuthnQuery: " + "Unable to obtain user assertions from CTS Repository. user = " + cacheKey, se);
        }
        if (list != null && !list.isEmpty()) {
            assertions = new ArrayList();
            for (Iterator iter = list.iterator(); iter.hasNext(); ) {
                String assertionStr = (String) iter.next();
                assertions.add(assertionFactory.createAssertion(assertionStr));
            }
        }
    } else {
        assertions = (List) IDPCache.assertionCache.get(cacheKey);
    }
    if ((assertions != null) && (!assertions.isEmpty())) {
        synchronized (assertions) {
            for (Iterator aIter = assertions.iterator(); aIter.hasNext(); ) {
                Assertion assertion = (Assertion) aIter.next();
                if (!assertion.isTimeValid()) {
                    if (SAML2Utils.debug.messageEnabled()) {
                        SAML2Utils.debug.message("AuthnQueryUtil.processAuthnQuery: " + " assertion " + assertion.getID() + " expired.");
                    }
                    continue;
                }
                List authnStmts = assertion.getAuthnStatements();
                for (Iterator asIter = authnStmts.iterator(); asIter.hasNext(); ) {
                    AuthnStatement authnStmt = (AuthnStatement) asIter.next();
                    AuthnContext authnStmtAC = authnStmt.getAuthnContext();
                    String sessionIndex = authnStmt.getSessionIndex();
                    String authnStmtACClassRef = authnStmtAC.getAuthnContextClassRef();
                    if (SAML2Utils.debug.messageEnabled()) {
                        SAML2Utils.debug.message("AuthnQueryUtil.processAuthnQuery: " + "authnStmtACClassRef is " + authnStmtACClassRef + ", sessionIndex = " + sessionIndex);
                    }
                    if ((qSessionIndex != null) && (qSessionIndex.length() != 0) && (!qSessionIndex.equals(sessionIndex))) {
                        continue;
                    }
                    if (requestedAC != null) {
                        List requestedACClassRefs = requestedAC.getAuthnContextClassRef();
                        String comparison = requestedAC.getComparison();
                        if (idpAuthnContextMapper.isAuthnContextMatching(requestedACClassRefs, authnStmtACClassRef, comparison, realm, authnAuthorityEntityID)) {
                            returnAssertions.add(assertion);
                            break;
                        }
                    } else {
                        returnAssertions.add(assertion);
                        break;
                    }
                }
            }
        }
    // end assertion iterator while.
    }
    ProtocolFactory protocolFactory = ProtocolFactory.getInstance();
    Response samlResp = protocolFactory.createResponse();
    if (!returnAssertions.isEmpty()) {
        samlResp.setAssertion(returnAssertions);
    }
    samlResp.setID(SAML2Utils.generateID());
    samlResp.setInResponseTo(authnQuery.getID());
    samlResp.setVersion(SAML2Constants.VERSION_2_0);
    samlResp.setIssueInstant(new Date());
    Status status = protocolFactory.createStatus();
    StatusCode statusCode = protocolFactory.createStatusCode();
    statusCode.setValue(SAML2Constants.SUCCESS);
    status.setStatusCode(statusCode);
    samlResp.setStatus(status);
    Issuer respIssuer = assertionFactory.createIssuer();
    respIssuer.setValue(authnAuthorityEntityID);
    samlResp.setIssuer(respIssuer);
    signResponse(samlResp, authnAuthorityEntityID, realm, false);
    return samlResp;
}
Also used : Status(com.sun.identity.saml2.protocol.Status) AuthnAuthorityDescriptorElement(com.sun.identity.saml2.jaxb.metadata.AuthnAuthorityDescriptorElement) IDPAccountMapper(com.sun.identity.saml2.plugins.IDPAccountMapper) IDPAuthnContextMapper(com.sun.identity.saml2.plugins.IDPAuthnContextMapper) Issuer(com.sun.identity.saml2.assertion.Issuer) NameID(com.sun.identity.saml2.assertion.NameID) ArrayList(java.util.ArrayList) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) SAML2MetaManager(com.sun.identity.saml2.meta.SAML2MetaManager) StatusCode(com.sun.identity.saml2.protocol.StatusCode) Date(java.util.Date) RequestedAuthnContext(com.sun.identity.saml2.protocol.RequestedAuthnContext) AuthnContext(com.sun.identity.saml2.assertion.AuthnContext) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ProtocolFactory(com.sun.identity.saml2.protocol.ProtocolFactory) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) RequestedAuthnContext(com.sun.identity.saml2.protocol.RequestedAuthnContext) AssertionFactory(com.sun.identity.saml2.assertion.AssertionFactory) Iterator(java.util.Iterator) AuthnStatement(com.sun.identity.saml2.assertion.AuthnStatement) ArrayList(java.util.ArrayList) List(java.util.List) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Example 25 with SAML2TokenRepositoryException

use of org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException in project OpenAM by OpenRock.

the class SPSSOFederate method initiateAuthnRequest.

/**
     * Parses the request parameters and builds the Authentication
     * Request to sent to the IDP.
     *
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     * @param spEntityID entityID of Service Provider.
     * @param idpEntityID entityID of Identity Provider.
     * @param paramsMap Map of all other parameters.The key in the
     *              map are the parameter names of the type String. 
     *              The values in the paramsMap are of the type List.
     *              Some of the possible keys are:RelayState,NameIDFormat,
     *              reqBinding, binding, AssertionConsumerServiceIndex,
     *              AttributeConsumingServiceIndex (currently not supported),
     *              isPassive, ForceAuthN, AllowCreate, Destination,
     *              AuthnContextDeclRef, AuthnContextClassRef,
     *              AuthComparison, Consent (currently not supported),
     *              AuthLevel, and sunamcompositeadvice.
     * @param auditor the auditor for logging SAML2 Events - may be null
     * @throws SAML2Exception if error initiating request to IDP.
     */
private static void initiateAuthnRequest(final HttpServletRequest request, final HttpServletResponse response, final String spEntityID, final String idpEntityID, final String realmName, final Map paramsMap, final SAML2EventLogger auditor) throws SAML2Exception {
    if (FSUtils.needSetLBCookieAndRedirect(request, response, false)) {
        return;
    }
    if (spEntityID == null) {
        SAML2Utils.debug.error("SPSSOFederate:Service Provider ID  is missing.");
        String[] data = { spEntityID };
        LogUtil.error(Level.INFO, LogUtil.INVALID_SP, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullSPEntityID"));
    }
    if (idpEntityID == null) {
        SAML2Utils.debug.error("SPSSOFederate: Identity Provider ID is missing .");
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.INVALID_IDP, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullIDPEntityID"));
    }
    String binding = getParameter(paramsMap, SAML2Constants.REQ_BINDING);
    if (binding == null) {
        binding = SAML2Constants.HTTP_REDIRECT;
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("SPSSOFederate: in initiateSSOFed");
        SAML2Utils.debug.message("SPSSOFederate: spEntityID is : " + spEntityID);
        SAML2Utils.debug.message("SPSSOFederate: idpEntityID : " + idpEntityID);
    }
    String realm = getRealm(realmName);
    try {
        // Retreive MetaData 
        if (sm == null) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("errorMetaManager"));
        }
        Map spConfigAttrsMap = getAttrsMapForAuthnReq(realm, spEntityID);
        // get SPSSODescriptor
        SPSSODescriptorElement spsso = getSPSSOForAuthnReq(realm, spEntityID);
        if (spsso == null) {
            String[] data = { spEntityID };
            LogUtil.error(Level.INFO, LogUtil.SP_METADATA_ERROR, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        }
        List extensionsList = getExtensionsList(spEntityID, realm);
        // get IDP Descriptor
        IDPSSODescriptorElement idpsso = getIDPSSOForAuthnReq(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"));
        }
        List ssoServiceList = idpsso.getSingleSignOnService();
        String ssoURL = getSSOURL(ssoServiceList, binding);
        if (ssoURL == null || ssoURL.length() == 0) {
            String[] data = { idpEntityID };
            LogUtil.error(Level.INFO, LogUtil.SSO_NOT_FOUND, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("ssoServiceNotfound"));
        }
        // create AuthnRequest 
        AuthnRequest authnRequest = createAuthnRequest(realm, spEntityID, paramsMap, spConfigAttrsMap, extensionsList, spsso, idpsso, ssoURL, false);
        if (null != auditor && null != authnRequest) {
            auditor.setRequestId(authnRequest.getID());
        }
        // invoke SP Adapter class if registered
        SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(spEntityID, realmName);
        if (spAdapter != null) {
            spAdapter.preSingleSignOnRequest(spEntityID, idpEntityID, realmName, request, response, authnRequest);
        }
        String authReqXMLString = authnRequest.toXMLString(true, true);
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("SPSSOFederate: AuthnRequest:" + authReqXMLString);
        }
        // Default URL if relayState not present? in providerConfig?
        // TODO get Default URL from metadata 
        String relayState = getParameter(paramsMap, SAML2Constants.RELAY_STATE);
        // Validate the RelayState URL.
        SAML2Utils.validateRelayStateURL(realm, spEntityID, relayState, SAML2Constants.SP_ROLE);
        // check if relayState is present and get the unique
        // id which will be appended to the SSO URL before
        // redirecting.
        String relayStateID = null;
        if (relayState != null && relayState.length() > 0) {
            relayStateID = getRelayStateID(relayState, authnRequest.getID());
        }
        if (binding.equals(SAML2Constants.HTTP_POST)) {
            String encodedReqMsg = getPostBindingMsg(idpsso, spsso, spConfigAttrsMap, authnRequest);
            SAML2Utils.postToTarget(request, response, "SAMLRequest", encodedReqMsg, "RelayState", relayStateID, ssoURL);
        } else {
            String redirect = getRedirect(authReqXMLString, relayStateID, ssoURL, idpsso, spsso, spConfigAttrsMap);
            response.sendRedirect(redirect);
        }
        String[] data = { ssoURL };
        LogUtil.access(Level.INFO, LogUtil.REDIRECT_TO_IDP, data, null);
        AuthnRequestInfo reqInfo = new AuthnRequestInfo(request, response, realm, spEntityID, idpEntityID, authnRequest, relayState, paramsMap);
        synchronized (SPCache.requestHash) {
            SPCache.requestHash.put(authnRequest.getID(), reqInfo);
        }
        if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            // sessionExpireTime is counted in seconds
            long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
            String key = authnRequest.getID();
            try {
                SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(key, new AuthnRequestInfoCopy(reqInfo), sessionExpireTime);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message("SPSSOFederate.initiateAuthnRequest:" + " SAVE AuthnRequestInfoCopy for requestID " + key);
                }
            } catch (SAML2TokenRepositoryException e) {
                SAML2Utils.debug.error("SPSSOFederate.initiateAuthnRequest: There was a problem saving the " + "AuthnRequestInfoCopy in the SAML2 Token Repository for requestID " + key, e);
                throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
            }
        }
    } catch (IOException ioe) {
        SAML2Utils.debug.error("SPSSOFederate: Exception :", ioe);
        throw new SAML2Exception(SAML2Utils.bundle.getString("errorCreatingAuthnRequest"));
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error("SPSSOFederate:Error retrieving metadata", sme);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
}
Also used : SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) List(java.util.List) IDPList(com.sun.identity.saml2.protocol.IDPList) ArrayList(java.util.ArrayList) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) SAML2ServiceProviderAdapter(com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter) Map(java.util.Map) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Aggregations

SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)25 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)18 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)14 List (java.util.List)12 SessionException (com.sun.identity.plugin.session.SessionException)9 ArrayList (java.util.ArrayList)9 HashMap (java.util.HashMap)8 Map (java.util.Map)8 SPSSOConfigElement (com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement)7 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)7 Issuer (com.sun.identity.saml2.assertion.Issuer)6 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)6 Status (com.sun.identity.saml2.protocol.Status)6 IOException (java.io.IOException)6 Iterator (java.util.Iterator)6 SessionProvider (com.sun.identity.plugin.session.SessionProvider)5 Assertion (com.sun.identity.saml2.assertion.Assertion)5 Date (java.util.Date)5 SingleLogoutServiceElement (com.sun.identity.saml2.jaxb.metadata.SingleLogoutServiceElement)4 SAML2MetaManager (com.sun.identity.saml2.meta.SAML2MetaManager)4