Search in sources :

Example 1 with NameIDInfoKey

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

the class BulkFederation method saml2FederateUser.

private void saml2FederateUser(String localUserId, String remoteUserId, BufferedWriter out) throws CLIException {
    SSOToken adminSSOToken = getAdminSSOToken();
    try {
        AMIdentity amid = IdUtils.getIdentity(adminSSOToken, localUserId);
        String nameIdValue = createNameIdentifier();
        NameID nameId = AssertionFactory.getInstance().createNameID();
        nameId.setFormat("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent");
        if (isIDP) {
            nameId.setNameQualifier(localEntityId);
            nameId.setSPNameQualifier(remoteEntityId);
        } else {
            nameId.setNameQualifier(remoteEntityId);
            nameId.setSPNameQualifier(localEntityId);
        }
        nameId.setValue(nameIdValue);
        String role = (isIDP) ? SAML2Constants.IDP_ROLE : SAML2Constants.SP_ROLE;
        NameIDInfoKey key = new NameIDInfoKey(nameIdValue, localEntityId, remoteEntityId);
        NameIDInfo info = new NameIDInfo(localEntityId, remoteEntityId, nameId, role, true);
        Map attributes = amid.getAttributes(saml2UserAttributesFed);
        Set setInfoKey = (Set) attributes.get(SAML2Constants.NAMEID_INFO_KEY);
        if ((setInfoKey == null) || setInfoKey.isEmpty()) {
            setInfoKey = new HashSet(2);
            attributes.put(SAML2Constants.NAMEID_INFO_KEY, setInfoKey);
        }
        setInfoKey.add(key.toValueString());
        Set setInfo = (Set) attributes.get(SAML2Constants.NAMEID_INFO);
        if ((setInfo == null) || setInfo.isEmpty()) {
            setInfo = new HashSet(2);
            attributes.put(SAML2Constants.NAMEID_INFO, setInfo);
        }
        setInfo.add(info.toValueString());
        amid.setAttributes(attributes);
        amid.store();
        out.write(remoteUserId + "|" + nameIdValue);
        out.newLine();
    } catch (SAML2Exception e) {
        debugError("BulkFederation.saml2FederateUser", e);
        Object[] param = { localUserId };
        throw new CLIException(MessageFormat.format(getResourceString("bulk-federation-cannot-federate"), param), ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (IOException e) {
        debugError("BulkFederation.saml2FederateUser", e);
        Object[] param = { localUserId };
        throw new CLIException(MessageFormat.format(getResourceString("bulk-federation-cannot-federate"), param), ExitCodes.REQUEST_CANNOT_BE_PROCESSED);
    } catch (IdRepoException e) {
        debugError("BulkFederation.saml2FederateUser", e);
        IOutput outputWriter = getOutputWriter();
        outputWriter.printlnError(e.getMessage());
    } catch (SSOException e) {
        debugError("BulkFederation.saml2FederateUser", e);
        IOutput outputWriter = getOutputWriter();
        outputWriter.printlnError(e.getMessage());
    }
}
Also used : NameIDInfo(com.sun.identity.saml2.common.NameIDInfo) SSOToken(com.iplanet.sso.SSOToken) HashSet(java.util.HashSet) Set(java.util.Set) NameID(com.sun.identity.saml2.assertion.NameID) IdRepoException(com.sun.identity.idm.IdRepoException) SSOException(com.iplanet.sso.SSOException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) IOutput(com.sun.identity.cli.IOutput) AMIdentity(com.sun.identity.idm.AMIdentity) CLIException(com.sun.identity.cli.CLIException) HashMap(java.util.HashMap) Map(java.util.Map) NameIDInfoKey(com.sun.identity.saml2.common.NameIDInfoKey) HashSet(java.util.HashSet)

Example 2 with NameIDInfoKey

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

the class AccountUtils method setAccountFederation.

/**
     * Sets the account federation information in the datastore for a user.
     * @param info <code>NameIDInfo</code> object to be set.
     * @param userID user identifier for which the account federation to be set.
     * @exception WSFederationException if any failure.
     */
public static void setAccountFederation(NameIDInfo info, String userID) throws WSFederationException {
    String classMethod = "AccountUtils.setAccountFederation: ";
    WSFederationUtils.debug.message(classMethod);
    if (info == null) {
        throw new WSFederationException(WSFederationUtils.bundle.getString("nullNameIDInfo"));
    }
    if (userID == null) {
        throw new WSFederationException(WSFederationUtils.bundle.getString("nullUserID"));
    }
    try {
        NameIDInfoKey infoKey = new NameIDInfoKey(info.getNameIDValue(), info.getHostEntityID(), info.getRemoteEntityID());
        if (WSFederationUtils.debug.messageEnabled()) {
            WSFederationUtils.debug.message(classMethod + "info to be set:" + info.toValueString() + "," + "infoKey to be set:" + infoKey.toValueString());
        }
        String filter = info.getHostEntityID() + DELIM + info.getRemoteEntityID() + DELIM;
        String nameIDInfoAttr = getNameIDInfoAttribute();
        String nameIDInfoKeyAttr = getNameIDInfoKeyAttribute();
        Set set = new HashSet();
        set.add(nameIDInfoAttr);
        set.add(nameIDInfoKeyAttr);
        Map map = new HashMap();
        Map existMap = WSFederationUtils.dsProvider.getAttributes(userID, set);
        if (existMap == null || existMap.isEmpty()) {
            Set set1 = new HashSet();
            set1.add(infoKey.toValueString());
            map.put(nameIDInfoKeyAttr, set1);
            Set set2 = new HashSet();
            set2.add(info.toValueString());
            map.put(nameIDInfoAttr, set2);
        } else {
            Set set1 = (Set) existMap.get(nameIDInfoAttr);
            if (set1 != null) {
                for (Iterator iter1 = set1.iterator(); iter1.hasNext(); ) {
                    String value = (String) iter1.next();
                    if (value.startsWith(filter)) {
                        iter1.remove();
                    }
                }
            } else {
                set1 = new HashSet();
            }
            set1.add(info.toValueString());
            map.put(nameIDInfoAttr, set1);
            Set set2 = (Set) existMap.get(nameIDInfoKeyAttr);
            if (set2 != null) {
                for (Iterator iter2 = set2.iterator(); iter2.hasNext(); ) {
                    String value = (String) iter2.next();
                    if (value.startsWith(filter)) {
                        iter2.remove();
                    }
                }
            } else {
                set2 = new HashSet();
            }
            set2.add(infoKey.toValueString());
            map.put(nameIDInfoKeyAttr, set2);
        }
        if (WSFederationUtils.debug.messageEnabled()) {
            WSFederationUtils.debug.message(classMethod + " set fedinfo " + map + " userID = " + userID);
        }
        WSFederationUtils.dsProvider.setAttributes(userID, map);
    } catch (DataStoreProviderException dse) {
        WSFederationUtils.debug.error(classMethod + "DataStoreProviderException", dse);
        throw new WSFederationException(dse);
    } catch (SAML2Exception se) {
        WSFederationUtils.debug.error(classMethod + "SAML2Exception", se);
        throw new WSFederationException(se);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) DataStoreProviderException(com.sun.identity.plugin.datastore.DataStoreProviderException) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) Iterator(java.util.Iterator) Map(java.util.Map) HashMap(java.util.HashMap) NameIDInfoKey(com.sun.identity.saml2.common.NameIDInfoKey) HashSet(java.util.HashSet)

Example 3 with NameIDInfoKey

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

the class SPSessionListener method sessionInvalidated.

/**
     *  Callback for SessionListener.
     *  It is used for cleaning up the SP session cache.
     *  
     *  @param session The session object
     */
public void sessionInvalidated(Object session) {
    String classMethod = "SPSessionListener.sessionInvalidated: ";
    HashMap paramsMap = new HashMap();
    NameIDInfoKey nameIdInfoKey = null;
    if (session == null || infoKeyString == null || sessionID == null) {
        return;
    }
    SessionProvider sessionProvider = null;
    SPFedSession fedSession = null;
    try {
        sessionProvider = SessionManager.getProvider();
    } catch (SessionException se) {
        return;
    }
    if (!sessionID.equals(sessionProvider.getSessionID(session))) {
        return;
    }
    List fedSessionList = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
    if (fedSessionList == null) {
        return;
    }
    try {
        Iterator iter = fedSessionList.iterator();
        while (iter.hasNext()) {
            fedSession = (SPFedSession) iter.next();
            if (fedSession.spTokenID.equals(sessionID)) {
                paramsMap.put(SAML2Constants.ROLE, SAML2Constants.SP_ROLE);
                String metaAlias = fedSession.metaAlias;
                nameIdInfoKey = NameIDInfoKey.parse(infoKeyString);
                String spEntityID = sm.getEntityByMetaAlias(metaAlias);
                String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
                BaseConfigType spConfig = sm.getSPSSOConfig(realm, spEntityID);
                if (spConfig != null) {
                    List spSessionSyncList = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.SP_SESSION_SYNC_ENABLED);
                    if (spEntityID != null && spSessionSyncList != null && (spSessionSyncList.size() != 0)) {
                        boolean spSessionSyncEnabled = ((String) spSessionSyncList.get(0)).equals(SAML2Constants.TRUE) ? true : false;
                        // is enabled
                        if (spSessionSyncEnabled) {
                            if (SAML2Utils.debug.messageEnabled()) {
                                SAML2Utils.debug.message(classMethod + "SP Session Synchronization flag " + "is enabled, initiating SLO to IDP");
                            }
                            initiateSPSingleLogout(metaAlias, realm, SAML2Constants.SOAP, nameIdInfoKey, fedSession, paramsMap);
                        }
                    }
                } else {
                    if (SAML2Utils.debug.messageEnabled()) {
                        SAML2Utils.debug.message(classMethod + "Unable to retrieve the SP config" + " data, spConfig is null");
                    }
                }
            }
        }
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error("SPSessionListener.sessionInvalidated:", sme);
    } catch (SAML2Exception se) {
        SAML2Utils.debug.error("SPSessionListener.sessionInvalidated:", se);
    } catch (SessionException s) {
        SAML2Utils.debug.error("IDPSessionListener.sessionInvalidated:", s);
    }
    synchronized (fedSessionList) {
        Iterator iter = fedSessionList.iterator();
        while (iter.hasNext()) {
            fedSession = (SPFedSession) iter.next();
            if (fedSession.spTokenID.equals(sessionID)) {
                iter.remove();
                if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                    saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
                }
            }
        }
        if (fedSessionList.isEmpty()) {
            SPCache.fedSessionListsByNameIDInfoKey.remove(infoKeyString);
        }
    }
}
Also used : BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) HashMap(java.util.HashMap) Iterator(java.util.Iterator) SessionException(com.sun.identity.plugin.session.SessionException) List(java.util.List) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) NameIDInfoKey(com.sun.identity.saml2.common.NameIDInfoKey) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Example 4 with NameIDInfoKey

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

the class SPACSUtils method saveInfoInMemory.

public static void saveInfoInMemory(SessionProvider sessionProvider, Object session, String sessionIndex, String metaAlias, NameIDInfo info, boolean isIDPProxy, boolean isTransient) throws SAML2Exception {
    String infoKeyString = (new NameIDInfoKey(info.getNameIDValue(), info.getHostEntityID(), info.getRemoteEntityID())).toValueString();
    String infoKeyAttribute = AccountUtils.getNameIDInfoKeyAttribute();
    String[] fromToken = null;
    try {
        fromToken = sessionProvider.getProperty(session, infoKeyAttribute);
        if (fromToken == null || fromToken.length == 0 || fromToken[0] == null || fromToken[0].length() == 0) {
            String[] values = { infoKeyString };
            sessionProvider.setProperty(session, infoKeyAttribute, values);
        } else {
            if (fromToken[0].indexOf(infoKeyString) == -1) {
                String[] values = { fromToken[0] + SAML2Constants.SECOND_DELIM + infoKeyString };
                sessionProvider.setProperty(session, infoKeyAttribute, values);
            }
        }
        if (isTransient) {
            String nameIDInfoStr = info.toValueString();
            String infoAttribute = AccountUtils.getNameIDInfoAttribute();
            String[] nameIDInfoStrs = sessionProvider.getProperty(session, infoAttribute);
            if (nameIDInfoStrs == null) {
                nameIDInfoStrs = new String[1];
                nameIDInfoStrs[0] = nameIDInfoStr;
            } else {
                Set nameIDInfoStrSet = new HashSet();
                for (int i = 0; i < nameIDInfoStrs.length; i++) {
                    nameIDInfoStrSet.add(nameIDInfoStrs[i]);
                }
                nameIDInfoStrSet.add(nameIDInfoStr);
                nameIDInfoStrs = (String[]) nameIDInfoStrSet.toArray(new String[nameIDInfoStrSet.size()]);
            }
            sessionProvider.setProperty(session, infoAttribute, nameIDInfoStrs);
        }
    } catch (SessionException sessE) {
        throw new SAML2Exception(sessE);
    }
    String tokenID = sessionProvider.getSessionID(session);
    if (!SPCache.isFedlet) {
        List fedSessions = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
        if (fedSessions == null) {
            synchronized (SPCache.fedSessionListsByNameIDInfoKey) {
                fedSessions = (List) SPCache.fedSessionListsByNameIDInfoKey.get(infoKeyString);
                if (fedSessions == null) {
                    fedSessions = new ArrayList();
                }
            }
            synchronized (fedSessions) {
                fedSessions.add(new SPFedSession(sessionIndex, tokenID, info, metaAlias));
                SPCache.fedSessionListsByNameIDInfoKey.put(infoKeyString, fedSessions);
            }
            if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
            }
            if (isIDPProxy) {
                //IDP Proxy 
                IDPSession idpSess = (IDPSession) IDPCache.idpSessionsBySessionID.get(tokenID);
                if (idpSess == null) {
                    idpSess = new IDPSession(session);
                    IDPCache.idpSessionsBySessionID.put(tokenID, idpSess);
                }
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message("Add Session Partner: " + info.getRemoteEntityID());
                }
                idpSess.addSessionPartner(new SAML2SessionPartner(info.getRemoteEntityID(), true));
            // end of IDP Proxy        
            }
        } else {
            synchronized (fedSessions) {
                Iterator iter = fedSessions.iterator();
                boolean found = false;
                while (iter.hasNext()) {
                    SPFedSession temp = (SPFedSession) iter.next();
                    String idpSessionIndex = null;
                    if (temp != null) {
                        idpSessionIndex = temp.idpSessionIndex;
                    }
                    if ((idpSessionIndex != null) && (idpSessionIndex.equals(sessionIndex))) {
                        temp.spTokenID = tokenID;
                        temp.info = info;
                        found = true;
                        break;
                    }
                }
                if (!found) {
                    fedSessions.add(new SPFedSession(sessionIndex, tokenID, info, metaAlias));
                    SPCache.fedSessionListsByNameIDInfoKey.put(infoKeyString, fedSessions);
                    if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                        saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
                    }
                }
            }
        }
        SPCache.fedSessionListsByNameIDInfoKey.put(infoKeyString, fedSessions);
        if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
            saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
        }
    }
    try {
        sessionProvider.addListener(session, new SPSessionListener(infoKeyString, tokenID));
    } catch (SessionException e) {
        SAML2Utils.debug.error("SPACSUtils.saveInfoInMemory: " + "Unable to add session listener.");
    }
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) SessionException(com.sun.identity.plugin.session.SessionException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) NameIDInfoKey(com.sun.identity.saml2.common.NameIDInfoKey) HashSet(java.util.HashSet)

Example 5 with NameIDInfoKey

use of com.sun.identity.saml2.common.NameIDInfoKey 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)10 NameIDInfoKey (com.sun.identity.saml2.common.NameIDInfoKey)9 HashMap (java.util.HashMap)6 HashSet (java.util.HashSet)6 List (java.util.List)5 Map (java.util.Map)5 SessionException (com.sun.identity.plugin.session.SessionException)4 NameID (com.sun.identity.saml2.assertion.NameID)4 ArrayList (java.util.ArrayList)4 Iterator (java.util.Iterator)4 Set (java.util.Set)4 SSOException (com.iplanet.sso.SSOException)2 CLIException (com.sun.identity.cli.CLIException)2 IOutput (com.sun.identity.cli.IOutput)2 AMIdentity (com.sun.identity.idm.AMIdentity)2 IdRepoException (com.sun.identity.idm.IdRepoException)2 NameIDInfo (com.sun.identity.saml2.common.NameIDInfo)2 BaseConfigType (com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType)2 IDPSSOConfigElement (com.sun.identity.saml2.jaxb.entityconfig.IDPSSOConfigElement)2 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)2