Search in sources :

Example 1 with FedletAdapter

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

Example 2 with FedletAdapter

use of com.sun.identity.saml2.plugins.FedletAdapter in project OpenAM by OpenRock.

the class LogoutUtil method doSLOBySOAP.

/**
     * Performs SOAP logout, this method will send LogoutResuest to IDP using
     * SOAP binding, and process LogoutResponse.
     * @param requestID Request id.
     * @param sloRequest  a string representation of LogoutRequest.
     * @param sloURL SOAP logout URL on IDP side.
     * @param realm  a string representation of LogoutRequest.
     * @param hostEntity  host entity is sending the request.
     * @param hostRole SOAP logout URL on IDP side.
     * @throws SAML2Exception if logout failed. 
     * @throws SessionException if logout failed. 
     */
private static void doSLOBySOAP(String requestID, LogoutRequest sloRequest, String sloURL, String realm, String hostEntity, String hostRole, HttpServletRequest request, HttpServletResponse response) throws SAML2Exception, SessionException {
    String sloRequestXMLString = sloRequest.toXMLString(true, true);
    if (debug.messageEnabled()) {
        debug.message("LogoutUtil.doSLOBySOAP : SLORequestXML: " + sloRequestXMLString + "\nSOAPURL : " + sloURL);
    }
    SOAPMessage resMsg = null;
    try {
        resMsg = SOAPCommunicator.getInstance().sendSOAPMessage(sloRequestXMLString, sloURL, true);
    } catch (SOAPException se) {
        debug.error("Unable to send SOAPMessage to IDP ", se);
        throw new SAML2Exception(se.getMessage());
    }
    // get the LogoutResponse element from SOAP message
    Element respElem = SOAPCommunicator.getInstance().getSamlpElement(resMsg, "LogoutResponse");
    LogoutResponse sloResponse = ProtocolFactory.getInstance().createLogoutResponse(respElem);
    String userId = null;
    // invoke SPAdapter for preSingleLogoutProcess : SP initiated SOAP
    if ((hostRole != null) && hostRole.equals(SAML2Constants.SP_ROLE)) {
        userId = SPSingleLogout.preSingleLogoutProcess(hostEntity, realm, request, response, null, sloRequest, sloResponse, SAML2Constants.SOAP);
    }
    if (sloResponse == null) {
        debug.error("LogoutUtil.doSLOBySoap : null response");
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullLogoutResponse"));
    }
    if (debug.messageEnabled()) {
        debug.message("LogoutUtil.doSLOBySOAP : " + "LogoutResponse without SOAP envelope:\n" + sloResponse.toXMLString());
    }
    Issuer resIssuer = sloResponse.getIssuer();
    String requestId = sloResponse.getInResponseTo();
    SAML2Utils.verifyResponseIssuer(realm, hostEntity, resIssuer, requestId);
    String remoteEntityID = sloResponse.getIssuer().getValue();
    verifySLOResponse(sloResponse, realm, remoteEntityID, hostEntity, hostRole);
    boolean success = checkSLOResponse(sloResponse, requestID);
    if (debug.messageEnabled()) {
        debug.message("Request success : " + success);
    }
    if (success == false) {
        if (SPCache.isFedlet) {
            FedletAdapter fedletAdapter = SAML2Utils.getFedletAdapterClass(hostEntity, realm);
            if (fedletAdapter != null) {
                fedletAdapter.onFedletSLOFailure(request, response, sloRequest, sloResponse, hostEntity, remoteEntityID, SAML2Constants.SOAP);
            }
        }
        throw new SAML2Exception(SAML2Utils.bundle.getString("sloFailed"));
    } else {
        // invoke SPAdapter for postSLOSuccess : SP inited SOAP 
        if ((hostRole != null) && hostRole.equals(SAML2Constants.SP_ROLE)) {
            if (SPCache.isFedlet) {
                FedletAdapter fedletAdapter = SAML2Utils.getFedletAdapterClass(hostEntity, realm);
                if (fedletAdapter != null) {
                    fedletAdapter.onFedletSLOSuccess(request, response, sloRequest, sloResponse, hostEntity, remoteEntityID, SAML2Constants.SOAP);
                }
            } else {
                SPSingleLogout.postSingleLogoutSuccess(hostEntity, realm, request, response, userId, sloRequest, sloResponse, SAML2Constants.SOAP);
            }
        }
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) FedletAdapter(com.sun.identity.saml2.plugins.FedletAdapter) LogoutResponse(com.sun.identity.saml2.protocol.LogoutResponse) Issuer(com.sun.identity.saml2.assertion.Issuer) SOAPException(javax.xml.soap.SOAPException) SingleLogoutServiceElement(com.sun.identity.saml2.jaxb.metadata.SingleLogoutServiceElement) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) Element(org.w3c.dom.Element) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement) SOAPMessage(javax.xml.soap.SOAPMessage)

Example 3 with FedletAdapter

use of com.sun.identity.saml2.plugins.FedletAdapter in project OpenAM by OpenRock.

the class SPSingleLogout method processLogoutResponse.

/**
     * Gets and processes the Single <code>LogoutResponse</code> from IDP,
     * destroys the local session, checks response's issuer
     * and inResponseTo.
     *
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     * @param samlResponse <code>LogoutResponse</code> in the
     *          XML string format.
     * @param relayState the target URL on successful
     * <code>LogoutResponse</code>.
     * @throws SAML2Exception if error processing
     *          <code>LogoutResponse</code>.
     * @throws SessionException if error processing
     *          <code>LogoutResponse</code>.
     */
public static Map<String, String> processLogoutResponse(HttpServletRequest request, HttpServletResponse response, String samlResponse, String relayState) throws SAML2Exception, SessionException {
    String method = "SPSingleLogout:processLogoutResponse : ";
    if (debug.messageEnabled()) {
        debug.message(method + "samlResponse : " + samlResponse);
        debug.message(method + "relayState : " + relayState);
    }
    String rmethod = request.getMethod();
    String binding = SAML2Constants.HTTP_REDIRECT;
    if (rmethod.equals("POST")) {
        binding = SAML2Constants.HTTP_POST;
    }
    String metaAlias = SAML2MetaUtils.getMetaAliasByUri(request.getRequestURI());
    if ((SPCache.isFedlet) && ((metaAlias == null) || (metaAlias.length() == 0))) {
        List spMetaAliases = sm.getAllHostedServiceProviderMetaAliases("/");
        if ((spMetaAliases != null) && !spMetaAliases.isEmpty()) {
            // get first one
            metaAlias = (String) spMetaAliases.get(0);
        }
    }
    if ((metaAlias == null) || (metaAlias.length() == 0)) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullSPEntityID"));
    }
    String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
    String spEntityID = sm.getEntityByMetaAlias(metaAlias);
    if (!SAML2Utils.isSPProfileBindingSupported(realm, spEntityID, SAML2Constants.SLO_SERVICE, binding)) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("unsupportedBinding"));
    }
    // Validate the RelayState URL.
    SAML2Utils.validateRelayStateURL(realm, spEntityID, relayState, SAML2Constants.SP_ROLE);
    LogoutResponse logoutRes = null;
    if (rmethod.equals("POST")) {
        logoutRes = LogoutUtil.getLogoutResponseFromPost(samlResponse, response);
    } else if (rmethod.equals("GET")) {
        String decodedStr = SAML2Utils.decodeFromRedirect(samlResponse);
        if (decodedStr == null) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("nullDecodedStrFromSamlResponse"));
        }
        logoutRes = ProtocolFactory.getInstance().createLogoutResponse(decodedStr);
    }
    if (logoutRes == null) {
        if (debug.messageEnabled()) {
            debug.message("SSingleLogout:processLogoutResponse: logoutRes " + "is null");
        }
        return null;
    }
    String idpEntityID = logoutRes.getIssuer().getValue();
    Issuer resIssuer = logoutRes.getIssuer();
    String inResponseTo = logoutRes.getInResponseTo();
    LogoutRequest logoutReq = (LogoutRequest) SPCache.logoutRequestIDHash.remove(inResponseTo);
    if (logoutReq == null) {
        logoutReq = (LogoutRequest) SAML2Store.getTokenFromStore(inResponseTo);
    }
    if (logoutReq == null && SAML2FailoverUtils.isSAML2FailoverEnabled()) {
        //check the samlFailover cache instead
        try {
            logoutReq = (LogoutRequest) SAML2FailoverUtils.retrieveSAML2Token(inResponseTo);
        } catch (SAML2TokenRepositoryException e) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("LogoutRequestIDandInResponseToDoNotMatch"));
        }
    }
    // invoke SPAdapter preSingleLogoutProcess
    String userId = null;
    if (!SPCache.isFedlet) {
        userId = preSingleLogoutProcess(spEntityID, realm, request, response, null, logoutReq, logoutRes, binding);
    }
    SAML2Utils.verifyResponseIssuer(realm, spEntityID, resIssuer, inResponseTo);
    boolean needToVerify = SAML2Utils.getWantLogoutResponseSigned(realm, spEntityID, SAML2Constants.SP_ROLE);
    if (debug.messageEnabled()) {
        debug.message(method + "metaAlias : " + metaAlias);
        debug.message(method + "realm : " + realm);
        debug.message(method + "idpEntityID : " + idpEntityID);
        debug.message(method + "spEntityID : " + spEntityID);
    }
    Map<String, String> infoMap = new HashMap<String, String>();
    infoMap.put("entityid", spEntityID);
    infoMap.put(SAML2Constants.REALM, realm);
    if (needToVerify) {
        boolean valid = false;
        if (rmethod.equals("GET")) {
            String queryString = request.getQueryString();
            valid = SAML2Utils.verifyQueryString(queryString, realm, SAML2Constants.SP_ROLE, idpEntityID);
        } else {
            valid = LogoutUtil.verifySLOResponse(logoutRes, realm, idpEntityID, spEntityID, SAML2Constants.SP_ROLE);
        }
        if (!valid) {
            debug.error("SPSingleLogout.processLogoutResponse: " + "Invalid signature in SLO Response.");
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInResponse"));
        }
        SPSSODescriptorElement spsso = sm.getSPSSODescriptor(realm, spEntityID);
        String loc = getSLOResponseLocationOrLocation(spsso, binding);
        if (!SAML2Utils.verifyDestination(logoutRes.getDestination(), loc)) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("invalidDestination"));
        }
    }
    if (inResponseTo == null || inResponseTo.length() == 0) {
        if (debug.messageEnabled()) {
            debug.message("LogoutResponse inResponseTo is null");
        }
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullInResponseToFromSamlResponse"));
    }
    if (logoutReq != null) {
        if (debug.messageEnabled()) {
            debug.message("LogoutResponse inResponseTo matches " + "LogoutRequest ID.");
        }
    } else {
        if (debug.messageEnabled()) {
            debug.message("LogoutResponse inResponseTo does not match " + "LogoutRequest ID.");
        }
        throw new SAML2Exception(SAML2Utils.bundle.getString("LogoutRequestIDandInResponseToDoNotMatch"));
    }
    infoMap.put("inResponseTo", inResponseTo);
    infoMap.put(SAML2Constants.RELAY_STATE, relayState);
    // destroy session
    try {
        Object session = sessionProvider.getSession(request);
        if ((session != null) && sessionProvider.isValid(session)) {
            sessionProvider.invalidateSession(session, request, response);
        }
    } catch (SessionException se) {
        debug.message("SPSingleLogout.processLogoutResponse() : Unable to invalidate session: " + se.getMessage());
    }
    if (!SPCache.isFedlet) {
        if (isSuccess(logoutRes)) {
            // invoke SPAdapter postSingleLogoutSucces
            postSingleLogoutSuccess(spEntityID, realm, request, response, userId, logoutReq, logoutRes, binding);
        } else {
            throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "sloFailed", null);
        }
    } else {
        // obtain fedlet adapter
        FedletAdapter fedletAdapter = SAML2Utils.getFedletAdapterClass(spEntityID, realm);
        if (fedletAdapter != null) {
            if (isSuccess(logoutRes)) {
                fedletAdapter.onFedletSLOSuccess(request, response, logoutReq, logoutRes, spEntityID, idpEntityID, binding);
            } else {
                fedletAdapter.onFedletSLOFailure(request, response, logoutReq, logoutRes, spEntityID, idpEntityID, binding);
                throw new SAML2Exception(SAML2Utils.BUNDLE_NAME, "sloFailed", null);
            }
        }
    }
    return infoMap;
}
Also used : LogoutResponse(com.sun.identity.saml2.protocol.LogoutResponse) Issuer(com.sun.identity.saml2.assertion.Issuer) HashMap(java.util.HashMap) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SessionException(com.sun.identity.plugin.session.SessionException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) FedletAdapter(com.sun.identity.saml2.plugins.FedletAdapter) List(java.util.List) ArrayList(java.util.ArrayList) LogoutRequest(com.sun.identity.saml2.protocol.LogoutRequest) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)

Example 4 with FedletAdapter

use of com.sun.identity.saml2.plugins.FedletAdapter in project OpenAM by OpenRock.

the class SAML2Utils method getFedletAdapterClass.

/**
     * Returns a <code>Fedlet</code> adapter class.
     *
     * @param spEntityID the entity id of the service provider
     * @param realm      the realm name
     * @return the <code>Fedlet</code> adapter class
     * @throws SAML2Exception if the operation is not successful
     */
public static FedletAdapter getFedletAdapterClass(String spEntityID, String realm) throws SAML2Exception {
    String classMethod = "SAML2Utils.getFedletAdapterClass: ";
    if (debug.messageEnabled()) {
        debug.message(classMethod + "get FedletAdapter for " + spEntityID + " under realm " + realm);
    }
    String fedletAdapterClassName = null;
    FedletAdapter fedletAdapterClass = null;
    try {
        fedletAdapterClassName = getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.FEDLET_ADAPTER_CLASS);
        if (debug.messageEnabled()) {
            debug.message(classMethod + "get FedletAdapter class " + fedletAdapterClassName);
        }
        if ((fedletAdapterClassName != null) && (fedletAdapterClassName.length() != 0)) {
            fedletAdapterClass = (FedletAdapter) SPCache.fedletAdapterClassCache.get(realm + spEntityID + fedletAdapterClassName);
            if (fedletAdapterClass == null) {
                fedletAdapterClass = (FedletAdapter) Class.forName(fedletAdapterClassName).newInstance();
                List env = getAllAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.FEDLET_ADAPTER_ENV);
                Map map = parseEnvList(env);
                map.put(FedletAdapter.HOSTED_ENTITY_ID, spEntityID);
                fedletAdapterClass.initialize(map);
                SPCache.fedletAdapterClassCache.put(realm + spEntityID + fedletAdapterClassName, fedletAdapterClass);
                if (debug.messageEnabled()) {
                    debug.message(classMethod + "create new FedletAdapter " + fedletAdapterClassName + " for " + spEntityID + " under realm " + realm);
                }
            } else {
                if (debug.messageEnabled()) {
                    debug.message(classMethod + "got the FedletAdapter " + fedletAdapterClassName + " from cache");
                }
            }
        }
    } catch (InstantiationException ex) {
        debug.error(classMethod + "Unable to get Fedlet Adapter class instance.", ex);
        throw new SAML2Exception(ex);
    } catch (ClassNotFoundException ex) {
        debug.error(classMethod + "Fedlet Adapter class not found.", ex);
        throw new SAML2Exception(ex);
    } catch (IllegalAccessException ex) {
        debug.error(classMethod + "Unable to get Fedlet Adapter class.", ex);
        throw new SAML2Exception(ex);
    }
    return fedletAdapterClass;
}
Also used : FedletAdapter(com.sun.identity.saml2.plugins.FedletAdapter) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

FedletAdapter (com.sun.identity.saml2.plugins.FedletAdapter)4 Issuer (com.sun.identity.saml2.assertion.Issuer)3 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)3 LogoutResponse (com.sun.identity.saml2.protocol.LogoutResponse)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 SessionException (com.sun.identity.plugin.session.SessionException)2 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)2 LogoutRequest (com.sun.identity.saml2.protocol.LogoutRequest)2 HashMap (java.util.HashMap)2 NameID (com.sun.identity.saml2.assertion.NameID)1 NameIDInfoKey (com.sun.identity.saml2.common.NameIDInfoKey)1 BaseConfigType (com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType)1 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)1 SingleLogoutServiceElement (com.sun.identity.saml2.jaxb.metadata.SingleLogoutServiceElement)1 Status (com.sun.identity.saml2.protocol.Status)1 Iterator (java.util.Iterator)1 ListIterator (java.util.ListIterator)1 Map (java.util.Map)1 SOAPException (javax.xml.soap.SOAPException)1