Search in sources :

Example 16 with Issuer

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

the class SPACSUtils method getResponseFromArtifact.

// Retrieves response using artifact profile.
private static Response getResponseFromArtifact(String samlArt, String hostEntityId, HttpServletRequest request, HttpServletResponse response, String orgName, SAML2MetaManager sm) throws SAML2Exception, IOException {
    // decide which IDP and which artifact resolution service
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("SPACSUtils.getResponseFromArtifact: " + "samlArt = " + samlArt);
    }
    Artifact art = null;
    try {
        art = ProtocolFactory.getInstance().createArtifact(samlArt.trim());
        String[] data = { samlArt.trim() };
        LogUtil.access(Level.INFO, LogUtil.RECEIVED_ARTIFACT, data, null);
    } catch (SAML2Exception se) {
        SAML2Utils.debug.error("SPACSUtils.getResponseFromArtifact: " + "Unable to decode and parse artifact string:" + samlArt);
        SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "errorObtainArtifact", SAML2Utils.bundle.getString("errorObtainArtifact"));
        throw se;
    }
    String idpEntityID = getIDPEntityID(art, request, response, orgName, sm);
    IDPSSODescriptorElement idp = null;
    try {
        idp = sm.getIDPSSODescriptor(orgName, idpEntityID);
    } catch (SAML2MetaException se) {
        String[] data = { orgName, idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.IDP_META_NOT_FOUND, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToGetIDPSSODescriptor", se.getMessage());
        throw se;
    }
    String location = getIDPArtifactResolutionServiceUrl(art.getEndpointIndex(), idpEntityID, idp, request, response);
    // create ArtifactResolve message
    ArtifactResolve resolve = null;
    SOAPMessage resMsg = null;
    try {
        resolve = ProtocolFactory.getInstance().createArtifactResolve();
        resolve.setID(SAML2Utils.generateID());
        resolve.setVersion(SAML2Constants.VERSION_2_0);
        resolve.setIssueInstant(new Date());
        resolve.setArtifact(art);
        resolve.setDestination(XMLUtils.escapeSpecialCharacters(location));
        Issuer issuer = AssertionFactory.getInstance().createIssuer();
        issuer.setValue(hostEntityId);
        resolve.setIssuer(issuer);
        String needArtiResolveSigned = SAML2Utils.getAttributeValueFromSSOConfig(orgName, idpEntityID, SAML2Constants.IDP_ROLE, SAML2Constants.WANT_ARTIFACT_RESOLVE_SIGNED);
        if (needArtiResolveSigned != null && needArtiResolveSigned.equals("true")) {
            // or save it somewhere?
            String signAlias = getAttributeValueFromSPSSOConfig(orgName, hostEntityId, sm, SAML2Constants.SIGNING_CERT_ALIAS);
            if (signAlias == null) {
                throw new SAML2Exception(SAML2Utils.bundle.getString("missingSigningCertAlias"));
            }
            KeyProvider kp = KeyUtil.getKeyProviderInstance();
            if (kp == null) {
                throw new SAML2Exception(SAML2Utils.bundle.getString("nullKeyProvider"));
            }
            resolve.sign(kp.getPrivateKey(signAlias), kp.getX509Certificate(signAlias));
        }
        String resolveString = resolve.toXMLString(true, true);
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("SPACSUtils.getResponseFromArtifact: " + "ArtifactResolve=" + resolveString);
        }
        SOAPConnection con = SOAPCommunicator.getInstance().openSOAPConnection();
        SOAPMessage msg = SOAPCommunicator.getInstance().createSOAPMessage(resolveString, true);
        IDPSSOConfigElement config = null;
        config = sm.getIDPSSOConfig(orgName, idpEntityID);
        location = SAML2Utils.fillInBasicAuthInfo(config, location);
        resMsg = con.call(msg, location);
    } catch (SAML2Exception s2e) {
        SAML2Utils.debug.error("SPACSUtils.getResponseFromArtifact: " + "couldn't create ArtifactResolve:", s2e);
        String[] data = { hostEntityId, art.getArtifactValue() };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_CREATE_ARTIFACT_RESOLVE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "errorCreateArtifactResolve", SAML2Utils.bundle.getString("errorCreateArtifactResolve"));
        throw s2e;
    } catch (SOAPException se) {
        SAML2Utils.debug.error("SPACSUtils.getResponseFromGet: " + "couldn't get ArtifactResponse. SOAP error:", se);
        String[] data = { hostEntityId, location };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_GET_SOAP_RESPONSE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "errorInSOAPCommunication", SAML2Utils.bundle.getString("errorInSOAPCommunication"));
        throw new SAML2Exception(se.getMessage());
    }
    Response result = getResponseFromSOAP(resMsg, resolve, request, response, idpEntityID, idp, orgName, hostEntityId, sm);
    String[] data = { hostEntityId, idpEntityID, art.getArtifactValue(), "" };
    if (LogUtil.isAccessLoggable(Level.FINE)) {
        data[3] = result.toXMLString();
    }
    LogUtil.access(Level.INFO, LogUtil.GOT_RESPONSE_FROM_ARTIFACT, data, null);
    return result;
}
Also used : KeyProvider(com.sun.identity.saml.xmlsig.KeyProvider) Issuer(com.sun.identity.saml2.assertion.Issuer) SOAPConnection(javax.xml.soap.SOAPConnection) IDPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.IDPSSOConfigElement) SOAPMessage(javax.xml.soap.SOAPMessage) Artifact(com.sun.identity.saml2.protocol.Artifact) Date(java.util.Date) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Response(com.sun.identity.saml2.protocol.Response) ArtifactResponse(com.sun.identity.saml2.protocol.ArtifactResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ArtifactResolve(com.sun.identity.saml2.protocol.ArtifactResolve) SOAPException(javax.xml.soap.SOAPException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 17 with Issuer

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

the class SPACSUtils method processResponseForFedlet.

/**
     * Processes response from Identity Provider to Fedlet (SP).
     * This will do all required protocol processing, include signature,
     * issuer and audience validation etc. A map containing processing
     * result will be returned. <br>
     * Here is a list of keys and values for the returned map: <br>
     * SAML2Constants.ATTRIBUTE_MAP -- Attribute map containing all attributes
     *                                 passed down from IDP inside the 
     *                                 Assertion. The value is a 
     *                                 <code>java.util.Map</code> whose keys 
     *                                 are attribute names and values are 
     *                                 <code>java.util.Set</code> of string 
     *                                 values for the attributes. <br>
     * SAML2Constants.RELAY_STATE -- Relay state, value is a string <br>
     * SAML2Constants.IDPENTITYID -- IDP entity ID, value is a string<br>
     * SAML2Constants.RESPONSE    -- Response object, value is an instance of 
     *                               com.sun.identity.saml2.protocol.Response
     * SAML2Constants.ASSERTION   -- Assertion object, value is an instance of 
     *                               com.sun.identity.saml2.assertion.Assertion
     * SAML2Constants.SUBJECT     -- Subject object, value is an instance of 
     *                               com.sun.identity.saml2.assertion.Subject
     * SAML2Constants.NAMEID      -- NameID object, value is an instance of 
     *                               com.sun.identity.saml2.assertion.NameID
     *
     * @param request HTTP Servlet request
     * @param response HTTP Servlet response.
     * @param out the print writer for writing out presentation
     *
     * @return <code>Map</code> which holds result of the processing.
     * @throws SAML2Exception if the processing failed due to server error.
     * @throws IOException if the processing failed due to IO error.
     * @throws SessionException if the processing failed due to session error.
     * @throws ServletException if the processing failed due to request error.
     *
     * @supported.api
     */
public static Map processResponseForFedlet(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws SAML2Exception, IOException, SessionException, ServletException {
    if ((request == null) || (response == null)) {
        throw new ServletException(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    String requestURL = request.getRequestURL().toString();
    SAML2MetaManager metaManager = new SAML2MetaManager();
    if (metaManager == null) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorMetaManager"));
    }
    String metaAlias = SAML2MetaUtils.getMetaAliasByUri(requestURL);
    if ((metaAlias == null) || (metaAlias.length() == 0)) {
        // Check in case metaAlias has been supplied as a parameter
        metaAlias = request.getParameter(SAML2MetaManager.NAME_META_ALIAS_IN_URI);
        if (metaAlias == null || metaAlias.length() == 0) {
            // pick the first available one
            List spMetaAliases = metaManager.getAllHostedServiceProviderMetaAliases("/");
            if ((spMetaAliases != null) && !spMetaAliases.isEmpty()) {
                // get first one
                metaAlias = (String) spMetaAliases.get(0);
            }
            if ((metaAlias == null) || (metaAlias.length() == 0)) {
                throw new ServletException(SAML2SDKUtils.bundle.getString("nullSPEntityID"));
            }
        }
    }
    String hostEntityId = null;
    try {
        hostEntityId = metaManager.getEntityByMetaAlias(metaAlias);
    } catch (SAML2MetaException sme) {
        SAML2SDKUtils.debug.error("SPACSUtils.processResponseForFedlet", sme);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
    }
    if (hostEntityId == null) {
        // logging?
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
    }
    // organization is always root org
    String orgName = "/";
    String relayState = request.getParameter(SAML2Constants.RELAY_STATE);
    SessionProvider sessionProvider = null;
    ResponseInfo respInfo = null;
    try {
        sessionProvider = SessionManager.getProvider();
    } catch (SessionException se) {
        SAML2SDKUtils.debug.error("SPACSUtils.processResponseForFedlet", se);
        throw new SAML2Exception(se);
    }
    respInfo = SPACSUtils.getResponse(request, response, orgName, hostEntityId, metaManager);
    Object newSession = null;
    // Throws a SAML2Exception if the response cannot be validated
    // or contains a non-Success StatusCode, invoking the SPAdapter SPI
    // for taking action on the failed validation.
    // The resulting exception has its redirectionDone flag set if
    // the SPAdapter issued a HTTP redirect.
    newSession = SPACSUtils.processResponse(request, response, out, metaAlias, null, respInfo, orgName, hostEntityId, metaManager, null);
    SAML2SDKUtils.debug.message("SSO SUCCESS");
    String[] redirected = sessionProvider.getProperty(newSession, SAML2Constants.RESPONSE_REDIRECTED);
    if ((redirected != null) && (redirected.length != 0) && redirected[0].equals("true")) {
        SAML2SDKUtils.debug.message("Already redirected in SPAdapter.");
        // response redirected already in SPAdapter
        return createMapForFedlet(respInfo, null, hostEntityId);
    }
    // redirect to relay state
    String finalUrl = SPACSUtils.getRelayState(relayState, orgName, hostEntityId, metaManager);
    String realFinalUrl = finalUrl;
    if (finalUrl != null && finalUrl.length() != 0) {
        try {
            realFinalUrl = sessionProvider.rewriteURL(newSession, finalUrl);
        } catch (SessionException se) {
            SAML2SDKUtils.debug.message("SPACSUtils.processRespForFedlet", se);
            realFinalUrl = finalUrl;
        }
    }
    String redirectUrl = SPACSUtils.getIntermediateURL(orgName, hostEntityId, metaManager);
    String realRedirectUrl = null;
    if (redirectUrl != null && redirectUrl.length() != 0) {
        if (realFinalUrl != null && realFinalUrl.length() != 0) {
            if (redirectUrl.indexOf("?") != -1) {
                redirectUrl += "&goto=";
            } else {
                redirectUrl += "?goto=";
            }
            redirectUrl += URLEncDec.encode(realFinalUrl);
            try {
                realRedirectUrl = sessionProvider.rewriteURL(newSession, redirectUrl);
            } catch (SessionException se) {
                SAML2SDKUtils.debug.message("SPACSUtils.processRespForFedlet: rewriting failed.", se);
                realRedirectUrl = redirectUrl;
            }
        } else {
            realRedirectUrl = redirectUrl;
        }
    } else {
        realRedirectUrl = finalUrl;
    }
    return createMapForFedlet(respInfo, realRedirectUrl, hostEntityId);
}
Also used : ServletException(javax.servlet.ServletException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SessionException(com.sun.identity.plugin.session.SessionException) List(java.util.List) ArrayList(java.util.ArrayList) SAML2MetaManager(com.sun.identity.saml2.meta.SAML2MetaManager) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Example 18 with Issuer

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

the class SPSSOFederate method createAuthnRequest.

/**
     * Create an AuthnRequest.
     *
     * @param realmName the authentication realm for this request
     * @param spEntityID the entity id for the service provider
     * @param paramsMap the map of parameters for the authentication request
     * @param spConfigMap the configuration map for the service provider
     * @param extensionsList a list of extendsions for the authentication request
     * @param spsso the SPSSODescriptorElement for theservcie provider
     * @param idpsso the IDPSSODescriptorElement for the identity provider
     * @param ssourl the url for the single sign on request
     * @param isForECP boolean to indicatge if the request originated from an ECP
     * @return a new AuthnRequest object
     * @throws SAML2Exception
     */
public static AuthnRequest createAuthnRequest(final String realmName, final String spEntityID, final Map paramsMap, final Map spConfigMap, final List extensionsList, final SPSSODescriptorElement spsso, final IDPSSODescriptorElement idpsso, final String ssourl, final boolean isForECP) throws SAML2Exception {
    // generate unique request ID
    String requestID = SAML2Utils.generateID();
    if ((requestID == null) || (requestID.length() == 0)) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("cannotGenerateID"));
    }
    // retrieve data from the params map and if not found get
    // default values from the SPConfig Attributes
    // destinationURI required if message is signed.
    String destinationURI = getParameter(paramsMap, SAML2Constants.DESTINATION);
    Boolean isPassive = doPassive(paramsMap, spConfigMap);
    Boolean isforceAuthn = isForceAuthN(paramsMap, spConfigMap);
    boolean allowCreate = isAllowCreate(paramsMap, spConfigMap);
    boolean includeRequestedAuthnContextFlag = includeRequestedAuthnContext(paramsMap, spConfigMap);
    String consent = getParameter(paramsMap, SAML2Constants.CONSENT);
    Extensions extensions = createExtensions(extensionsList);
    String nameIDPolicyFormat = getParameter(paramsMap, SAML2Constants.NAMEID_POLICY_FORMAT);
    // get NameIDPolicy Element 
    NameIDPolicy nameIDPolicy = createNameIDPolicy(spEntityID, nameIDPolicyFormat, allowCreate, spsso, idpsso, realmName, paramsMap);
    Issuer issuer = createIssuer(spEntityID);
    Integer acsIndex = getIndex(paramsMap, SAML2Constants.ACS_URL_INDEX);
    Integer attrIndex = getIndex(paramsMap, SAML2Constants.ATTR_INDEX);
    String protocolBinding = isForECP ? SAML2Constants.PAOS : getParameter(paramsMap, "binding");
    OrderedSet acsSet = getACSUrl(spsso, protocolBinding);
    String acsURL = (String) acsSet.get(0);
    protocolBinding = (String) acsSet.get(1);
    if (!SAML2Utils.isSPProfileBindingSupported(realmName, spEntityID, SAML2Constants.ACS_SERVICE, protocolBinding)) {
        SAML2Utils.debug.error("SPSSOFederate.createAuthnRequest:" + protocolBinding + "is not supported for " + spEntityID);
        String[] data = { spEntityID, protocolBinding };
        LogUtil.error(Level.INFO, LogUtil.BINDING_NOT_SUPPORTED, data, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
    }
    AuthnRequest authnReq = ProtocolFactory.getInstance().createAuthnRequest();
    if (!isForECP) {
        if ((destinationURI == null) || (destinationURI.length() == 0)) {
            authnReq.setDestination(XMLUtils.escapeSpecialCharacters(ssourl));
        } else {
            authnReq.setDestination(XMLUtils.escapeSpecialCharacters(destinationURI));
        }
    }
    authnReq.setConsent(consent);
    authnReq.setIsPassive(isPassive);
    authnReq.setForceAuthn(isforceAuthn);
    authnReq.setAttributeConsumingServiceIndex(attrIndex);
    authnReq.setAssertionConsumerServiceIndex(acsIndex);
    authnReq.setAssertionConsumerServiceURL(XMLUtils.escapeSpecialCharacters(acsURL));
    authnReq.setProtocolBinding(protocolBinding);
    authnReq.setIssuer(issuer);
    authnReq.setNameIDPolicy(nameIDPolicy);
    if (includeRequestedAuthnContextFlag) {
        authnReq.setRequestedAuthnContext(createReqAuthnContext(realmName, spEntityID, paramsMap, spConfigMap));
    }
    if (extensions != null) {
        authnReq.setExtensions(extensions);
    }
    // Required attributes in authn request
    authnReq.setID(requestID);
    authnReq.setVersion(SAML2Constants.VERSION_2_0);
    authnReq.setIssueInstant(new Date());
    //IDP Proxy 
    Boolean enableIDPProxy = getAttrValueFromMap(spConfigMap, SAML2Constants.ENABLE_IDP_PROXY);
    if ((enableIDPProxy != null) && enableIDPProxy.booleanValue()) {
        Scoping scoping = ProtocolFactory.getInstance().createScoping();
        String proxyCountParam = getParameter(spConfigMap, SAML2Constants.IDP_PROXY_COUNT);
        if (proxyCountParam != null && (!proxyCountParam.equals(""))) {
            scoping.setProxyCount(new Integer(proxyCountParam));
        }
        List proxyIDPs = (List) spConfigMap.get(SAML2Constants.IDP_PROXY_LIST);
        if (proxyIDPs != null && !proxyIDPs.isEmpty()) {
            Iterator iter = proxyIDPs.iterator();
            ArrayList list = new ArrayList();
            while (iter.hasNext()) {
                IDPEntry entry = ProtocolFactory.getInstance().createIDPEntry();
                entry.setProviderID((String) iter.next());
                list.add(entry);
            }
            IDPList idpList = ProtocolFactory.getInstance().createIDPList();
            idpList.setIDPEntries(list);
            scoping.setIDPList(idpList);
        }
        authnReq.setScoping(scoping);
    }
    return authnReq;
}
Also used : OrderedSet(com.sun.identity.shared.datastruct.OrderedSet) NameIDPolicy(com.sun.identity.saml2.protocol.NameIDPolicy) Issuer(com.sun.identity.saml2.assertion.Issuer) ArrayList(java.util.ArrayList) IDPList(com.sun.identity.saml2.protocol.IDPList) Extensions(com.sun.identity.saml2.protocol.Extensions) Date(java.util.Date) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) Scoping(com.sun.identity.saml2.protocol.Scoping) Iterator(java.util.Iterator) List(java.util.List) IDPList(com.sun.identity.saml2.protocol.IDPList) ArrayList(java.util.ArrayList) IDPEntry(com.sun.identity.saml2.protocol.IDPEntry)

Example 19 with Issuer

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

the class SPSSOFederate method createIssuer.

/* Create Issuer */
private static Issuer createIssuer(String spEntityID) throws SAML2Exception {
    Issuer issuer = AssertionFactory.getInstance().createIssuer();
    issuer.setValue(spEntityID);
    return issuer;
}
Also used : Issuer(com.sun.identity.saml2.assertion.Issuer)

Example 20 with Issuer

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

the class SPSingleLogout method processLogoutRequest.

/**
     * Gets and processes the Single <code>LogoutRequest</code> from IDP
     * and return <code>LogoutResponse</code>.
     *
     * @param logoutReq <code>LogoutRequest</code> from IDP
     * @param spEntityID name of host entity ID.
     * @param realm name of host entity.
     * @param request HTTP servlet request.
     * @param response HTTP servlet response.
     * @param isLBReq true if the request is for load balancing.
     * @param binding value of <code>SAML2Constants.HTTP_REDIRECT</code> or
     *        <code>SAML2Constants.SOAP</code>.
     * @param isVerified true if the request is verified already.
     * @return LogoutResponse the target URL on successful
     * <code>LogoutRequest</code>.
     */
public static LogoutResponse processLogoutRequest(LogoutRequest logoutReq, String spEntityID, String realm, HttpServletRequest request, HttpServletResponse response, boolean isLBReq, boolean destroySession, String binding, boolean isVerified) {
    final String method = "processLogoutRequest : ";
    NameID nameID = null;
    Status status = null;
    Issuer issuer = null;
    String idpEntity = logoutReq.getIssuer().getValue();
    String userId = null;
    try {
        do {
            // TODO: check the NotOnOrAfter attribute of LogoutRequest
            issuer = logoutReq.getIssuer();
            String requestId = logoutReq.getID();
            SAML2Utils.verifyRequestIssuer(realm, spEntityID, issuer, requestId);
            issuer = SAML2Utils.createIssuer(spEntityID);
            // get SessionIndex and NameID form LogoutRequest
            List siList = logoutReq.getSessionIndex();
            int numSI = 0;
            if (siList != null) {
                numSI = siList.size();
                if (debug.messageEnabled()) {
                    debug.message(method + "Number of session indices in the logout request is " + numSI);
                }
            }
            nameID = LogoutUtil.getNameIDFromSLORequest(logoutReq, realm, spEntityID, SAML2Constants.SP_ROLE);
            if (nameID == null) {
                debug.error(method + "LogoutRequest does not contain Name ID");
                status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("missing_name_identifier"));
                break;
            }
            String infoKeyString = null;
            infoKeyString = (new NameIDInfoKey(nameID.getValue(), spEntityID, idpEntity)).toValueString();
            if (debug.messageEnabled()) {
                debug.message(method + "infokey=" + infoKeyString);
            }
            if (SPCache.isFedlet) {
                // verify request
                if (!isVerified && !LogoutUtil.verifySLORequest(logoutReq, realm, idpEntity, spEntityID, SAML2Constants.SP_ROLE)) {
                    throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
                }
                // obtain fedlet adapter
                FedletAdapter fedletAdapter = SAML2Utils.getFedletAdapterClass(spEntityID, realm);
                boolean result = false;
                if (fedletAdapter != null) {
                    // call adapter to do real logout
                    result = fedletAdapter.doFedletSLO(request, response, logoutReq, spEntityID, idpEntity, siList, nameID.getValue(), binding);
                }
                if (result) {
                    status = SUCCESS_STATUS;
                } else {
                    status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("appLogoutFailed"));
                }
                break;
            }
            List list = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
            if (debug.messageEnabled()) {
                debug.message(method + "SPFedsessions=" + list);
            }
            if ((list == null) || list.isEmpty()) {
                String spQ = nameID.getSPNameQualifier();
                if ((spQ == null) || (spQ.length() == 0)) {
                    infoKeyString = (new NameIDInfoKey(nameID.getValue(), spEntityID, nameID.getNameQualifier())).toValueString();
                    list = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
                }
            }
            boolean foundPeer = false;
            List remoteServiceURLs = null;
            if (isLBReq) {
                remoteServiceURLs = FSUtils.getRemoteServiceURLs(request);
                foundPeer = remoteServiceURLs != null && !remoteServiceURLs.isEmpty();
            }
            if (debug.messageEnabled()) {
                debug.message(method + "isLBReq = " + isLBReq + ", foundPeer = " + foundPeer);
            }
            if (list == null || list.isEmpty()) {
                if (foundPeer) {
                    boolean peerError = false;
                    for (Iterator iter = remoteServiceURLs.iterator(); iter.hasNext(); ) {
                        String remoteLogoutURL = getRemoteLogoutURL((String) iter.next(), request);
                        LogoutResponse logoutRes = LogoutUtil.forwardToRemoteServer(logoutReq, remoteLogoutURL);
                        if ((logoutRes != null) && !isNameNotFound(logoutRes)) {
                            if (isSuccess(logoutRes)) {
                                if (numSI > 0) {
                                    siList = LogoutUtil.getSessionIndex(logoutRes);
                                    if (siList == null || siList.isEmpty()) {
                                        peerError = false;
                                        break;
                                    }
                                }
                            } else {
                                peerError = true;
                            }
                        }
                    }
                    if (peerError || (siList != null && siList.size() > 0)) {
                        status = PARTIAL_LOGOUT_STATUS;
                    } else {
                        status = SUCCESS_STATUS;
                    }
                } else {
                    debug.error(method + "invalid Name ID received");
                    status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, SAML2Utils.bundle.getString("invalid_name_identifier"));
                }
                break;
            } else {
                // find the session, do signature validation
                if (!isVerified && !LogoutUtil.verifySLORequest(logoutReq, realm, logoutReq.getIssuer().getValue(), spEntityID, SAML2Constants.SP_ROLE)) {
                    throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInRequest"));
                }
                // invoke SPAdapter for preSingleLogoutProcess
                try {
                    String tokenId = ((SPFedSession) list.iterator().next()).spTokenID;
                    Object token = sessionProvider.getSession(tokenId);
                    userId = sessionProvider.getPrincipalName(token);
                    if (SAML2Utils.debug.messageEnabled()) {
                        SAML2Utils.debug.message("SPSingleLogout." + "processLogoutRequest, user = " + userId);
                    }
                } catch (SessionException ex) {
                    if (SAML2Utils.debug.messageEnabled()) {
                        SAML2Utils.debug.message("SPSingleLogout." + "processLogoutRequest", ex);
                    }
                }
                userId = preSingleLogoutProcess(spEntityID, realm, request, response, userId, logoutReq, null, binding);
            }
            // get application logout URL 
            BaseConfigType spConfig = SAML2Utils.getSAML2MetaManager().getSPSSOConfig(realm, spEntityID);
            List appLogoutURL = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.APP_LOGOUT_URL);
            if (debug.messageEnabled()) {
                debug.message("IDPLogoutUtil.processLogoutRequest: " + "external app logout URL= " + appLogoutURL);
            }
            if (numSI == 0) {
                // logout all fed sessions for this user
                // between this SP and the IDP
                List tokenIDsToBeDestroyed = new ArrayList();
                synchronized (list) {
                    Iterator iter = list.listIterator();
                    while (iter.hasNext()) {
                        SPFedSession fedSession = (SPFedSession) iter.next();
                        tokenIDsToBeDestroyed.add(fedSession.spTokenID);
                        iter.remove();
                        if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                            saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
                        }
                    }
                }
                for (Iterator iter = tokenIDsToBeDestroyed.listIterator(); iter.hasNext(); ) {
                    String tokenID = (String) iter.next();
                    Object token = null;
                    try {
                        token = sessionProvider.getSession(tokenID);
                    } catch (SessionException se) {
                        debug.error(method + "Could not create session from token ID = " + tokenID);
                        continue;
                    }
                    if (debug.messageEnabled()) {
                        debug.message(method + "destroy token " + tokenID);
                    }
                    // handle external application logout if configured
                    if ((appLogoutURL != null) && (appLogoutURL.size() != 0)) {
                        SAML2Utils.postToAppLogout(request, (String) appLogoutURL.get(0), token);
                    }
                    if (destroySession) {
                        sessionProvider.invalidateSession(token, request, response);
                    }
                }
                if (foundPeer) {
                    boolean peerError = false;
                    for (Iterator iter = remoteServiceURLs.iterator(); iter.hasNext(); ) {
                        String remoteLogoutURL = getRemoteLogoutURL((String) iter.next(), request);
                        LogoutResponse logoutRes = LogoutUtil.forwardToRemoteServer(logoutReq, remoteLogoutURL);
                        if ((logoutRes == null) || !(isSuccess(logoutRes) || isNameNotFound(logoutRes))) {
                            peerError = true;
                        }
                    }
                    if (peerError) {
                        status = PARTIAL_LOGOUT_STATUS;
                    } else {
                        status = SUCCESS_STATUS;
                    }
                }
            } else {
                // logout only those fed sessions specified
                // in logout request session list
                String sessionIndex = null;
                List siNotFound = new ArrayList();
                for (int i = 0; i < numSI; i++) {
                    sessionIndex = (String) siList.get(i);
                    String tokenIDToBeDestroyed = null;
                    synchronized (list) {
                        Iterator iter = list.listIterator();
                        while (iter.hasNext()) {
                            SPFedSession fedSession = (SPFedSession) iter.next();
                            if (sessionIndex.equals(fedSession.idpSessionIndex)) {
                                if (debug.messageEnabled()) {
                                    debug.message(method + " found si + " + sessionIndex);
                                }
                                tokenIDToBeDestroyed = fedSession.spTokenID;
                                iter.remove();
                                if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                                    saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
                                }
                                break;
                            }
                        }
                    }
                    if (tokenIDToBeDestroyed != null) {
                        try {
                            Object token = sessionProvider.getSession(tokenIDToBeDestroyed);
                            if (debug.messageEnabled()) {
                                debug.message(method + "destroy token (2) " + tokenIDToBeDestroyed);
                            }
                            // handle external application logout 
                            if ((appLogoutURL != null) && (appLogoutURL.size() != 0)) {
                                SAML2Utils.postToAppLogout(request, (String) appLogoutURL.get(0), token);
                            }
                            if (destroySession) {
                                sessionProvider.invalidateSession(token, request, response);
                            }
                        } catch (SessionException se) {
                            debug.error(method + "Could not create " + "session from token ID = " + tokenIDToBeDestroyed);
                        }
                    } else {
                        siNotFound.add(sessionIndex);
                    }
                }
                if (isLBReq) {
                    if (foundPeer && !siNotFound.isEmpty()) {
                        boolean peerError = false;
                        LogoutRequest lReq = copyAndMakeMutable(logoutReq);
                        for (Iterator iter = remoteServiceURLs.iterator(); iter.hasNext(); ) {
                            lReq.setSessionIndex(siNotFound);
                            String remoteLogoutURL = getRemoteLogoutURL((String) iter.next(), request);
                            LogoutResponse logoutRes = LogoutUtil.forwardToRemoteServer(lReq, remoteLogoutURL);
                            if ((logoutRes != null) && !isNameNotFound(logoutRes)) {
                                if (isSuccess(logoutRes)) {
                                    siNotFound = LogoutUtil.getSessionIndex(logoutRes);
                                } else {
                                    peerError = true;
                                }
                            }
                            if (debug.messageEnabled()) {
                                debug.message(method + "siNotFound = " + siNotFound);
                            }
                            if (siNotFound == null || siNotFound.isEmpty()) {
                                peerError = false;
                                break;
                            }
                        }
                        if (peerError || (siNotFound != null && !siNotFound.isEmpty())) {
                            status = PARTIAL_LOGOUT_STATUS;
                        } else {
                            status = SUCCESS_STATUS;
                        }
                    } else {
                        status = SUCCESS_STATUS;
                    }
                } else {
                    if (siNotFound.isEmpty()) {
                        status = SUCCESS_STATUS;
                    } else {
                        status = SAML2Utils.generateStatus(SAML2Constants.SUCCESS, SAML2Utils.bundle.getString("requestSuccess"));
                        LogoutUtil.setSessionIndex(status, siNotFound);
                    }
                }
            }
        } while (false);
    } catch (SessionException se) {
        debug.error("processLogoutRequest: ", se);
        status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, se.toString());
    } catch (SAML2Exception e) {
        debug.error("processLogoutRequest: " + "failed to create response", e);
        status = SAML2Utils.generateStatus(SAML2Constants.RESPONDER, e.toString());
    }
    // create LogoutResponse
    if (spEntityID == null) {
        spEntityID = nameID.getSPNameQualifier();
    }
    LogoutResponse logResponse = LogoutUtil.generateResponse(status, logoutReq.getID(), issuer, realm, SAML2Constants.SP_ROLE, idpEntity);
    if (isSuccess(logResponse)) {
        // invoke SPAdapter for postSingleLogoutSuccess
        postSingleLogoutSuccess(spEntityID, realm, request, response, userId, logoutReq, logResponse, binding);
    }
    return logResponse;
}
Also used : Status(com.sun.identity.saml2.protocol.Status) LogoutResponse(com.sun.identity.saml2.protocol.LogoutResponse) NameID(com.sun.identity.saml2.assertion.NameID) Issuer(com.sun.identity.saml2.assertion.Issuer) ArrayList(java.util.ArrayList) SessionException(com.sun.identity.plugin.session.SessionException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) FedletAdapter(com.sun.identity.saml2.plugins.FedletAdapter) ListIterator(java.util.ListIterator) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) LogoutRequest(com.sun.identity.saml2.protocol.LogoutRequest) NameIDInfoKey(com.sun.identity.saml2.common.NameIDInfoKey)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)48 Issuer (com.sun.identity.saml2.assertion.Issuer)42 Date (java.util.Date)24 List (java.util.List)20 ArrayList (java.util.ArrayList)19 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)15 Element (org.w3c.dom.Element)15 Assertion (com.sun.identity.saml2.assertion.Assertion)13 Response (com.sun.identity.saml2.protocol.Response)13 SessionException (com.sun.identity.plugin.session.SessionException)12 X509Certificate (java.security.cert.X509Certificate)12 EncryptedAssertion (com.sun.identity.saml2.assertion.EncryptedAssertion)11 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)11 HttpServletResponse (javax.servlet.http.HttpServletResponse)11 Node (org.w3c.dom.Node)10 NodeList (org.w3c.dom.NodeList)10 AssertionFactory (com.sun.identity.saml2.assertion.AssertionFactory)8 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)8 ProtocolFactory (com.sun.identity.saml2.protocol.ProtocolFactory)8 Status (com.sun.identity.saml2.protocol.Status)8