Search in sources :

Example 11 with Status

use of com.sun.identity.saml2.protocol.Status in project OpenAM by OpenRock.

the class SMAdapter method postSingleSignOnSuccess.

/**
     * Invokes after Single-Sign-On processing succeeded.
     * @param hostedEntityID Entity ID for the hosted SP
     * @param realm Realm of the hosted SP.
     * @param request servlet request
     * @param response servlet response
     * @param session user's session
     * @param authnRequest the original authentication request sent from SP, 
     *       null if this is IDP initiated SSO.
     * @param ssoResponse response from IDP 
     * @param profile protocol profile used, one of the following values: 
     *     <code>SAML2Constants.HTTP_POST</code>, 
     *     <code>SAML2Constants.HTTP_ARTIFACT</code>,
     *     <code>SAML2Constants.PAOS</code>
     * @param isFederation true if this is federation case, false otherwise.
     * @return true if browser redirection happened after processing, 
     *     false otherwise. Default to false. 
     * @exception SAML2Exception if user want to fail the process.
     */
public boolean postSingleSignOnSuccess(String hostedEntityID, String realm, HttpServletRequest request, HttpServletResponse response, Object session, AuthnRequest authnRequest, Response ssoResponse, String profile, boolean isFederation) throws SAML2Exception {
    try {
        SSOToken ssoToken = (SSOToken) session;
        String famSession = ssoToken.getTokenID().toString();
        /*
            Cookie[] cookies = request.getCookies();
            for (int i=0; i < cookies.length; i++) {
                 Cookie cookie = cookies[i];
                 if(cookie.getName().equals(famCookieName)) {
                    famSession = cookie.getValue();
                 }
            }
*/
        if (famSession == null) {
            throw new SAML2Exception("No OpenSSO Session found");
        }
        UserCredentials uc = new UserCredentials("FMTOKEN", "FMTOKEN" + famSession);
        SessionDef sd = new SessionDef();
        ResourceContextDef rcd = new ResourceContextDef(agentID, agentHostName, resource, "GET");
        RealmDef rd = new RealmDef();
        int retCode = agentAPI.isProtected(agentIP, rcd, rd);
        if (retCode != AgentAPI.YES) {
            System.out.println("Agent is not protected.");
            throw new SAML2Exception("Agent is not protected");
        }
        AttributeList al = new AttributeList();
        int status = agentAPI.login(agentIP, rcd, rd, uc, sd, al);
        if (status != AgentAPI.YES) {
            throw new SAML2Exception("Agent authentication failed");
        }
        Cookie smCookie = new Cookie(smCookieName, sd.spec);
        smCookie.setDomain(cookieDomain);
        response.addCookie(smCookie);
        return false;
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new SAML2Exception(ex.getMessage());
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Cookie(javax.servlet.http.Cookie) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 12 with Status

use of com.sun.identity.saml2.protocol.Status in project OpenAM by OpenRock.

the class XACMLAuthzDecisionQueryHandler method handleQuery.

/**
     * Processes an XACMLAuthzDecisionQuery and retruns a SAML2 Response.
     *
     * @param pdpEntityId EntityID of PDP
     * @param pepEntityId EntityID of PEP
     * @param samlpRequest SAML2 Request, an XAMLAuthzDecisionQuery
     * @param soapMessage SOAPMessage that carried the SAML2 Request
     * @return SAML2 Response with an XAMLAuthzDecisionStatement
     * @exception SAML2Exception if the query can not be handled
     */
public com.sun.identity.saml2.protocol.Response handleQuery(String pdpEntityId, String pepEntityId, RequestAbstract samlpRequest, SOAPMessage soapMessage) throws SAML2Exception {
    //TODO: logging, i18n
    //TODO: long term, allow different mapper impls for  different
    //combination of pdp, pep
    SubjectMapper subjectMapper = new FMSubjectMapper();
    subjectMapper.initialize(pdpEntityId, pepEntityId, null);
    ResourceMapper resourceMapper = new FMResourceMapper();
    resourceMapper.initialize(pdpEntityId, pepEntityId, null);
    ActionMapper actionMapper = new FMActionMapper();
    actionMapper.initialize(pdpEntityId, pepEntityId, null);
    EnvironmentMapper environmentMapper = new FMEnvironmentMapper();
    environmentMapper.initialize(pdpEntityId, pepEntityId, null);
    ResultMapper resultMapper = new FMResultMapper();
    resultMapper.initialize(pdpEntityId, pepEntityId, null);
    boolean evaluationFailed = false;
    String statusCodeValue = null;
    if (XACMLSDKUtils.debug.messageEnabled()) {
        XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery(), entering" + ":pdpEntityId=" + pdpEntityId + ":pepEntityId=" + pepEntityId + ":samlpRequest=\n" + samlpRequest.toXMLString(true, true) + ":soapMessage=\n" + soapMessage);
    }
    Request xacmlRequest = ((XACMLAuthzDecisionQuery) samlpRequest).getRequest();
    boolean returnContext = ((XACMLAuthzDecisionQuery) samlpRequest).getReturnContext();
    SSOToken ssoToken = null;
    String resourceName = null;
    String serviceName = null;
    String actionName = null;
    Map environment = null;
    boolean booleanDecision = false;
    try {
        //get native sso token
        ssoToken = (SSOToken) subjectMapper.mapToNativeSubject(xacmlRequest.getSubjects());
        if (ssoToken == null) {
            //TODO: log message and fill missing attribute details 
            statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
            evaluationFailed = true;
        } else {
            if (XACMLSDKUtils.debug.messageEnabled()) {
                XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery()," + "created ssoToken");
            }
        }
        if (ssoToken != null) {
            //get native service name, resource name 
            List resources = xacmlRequest.getResources();
            Resource resource = null;
            if (!resources.isEmpty()) {
                //We deal with only one resource for now
                resource = (Resource) resources.get(0);
            }
            if (resource != null) {
                String[] resourceService = resourceMapper.mapToNativeResource(resource);
                if (resourceService != null) {
                    if (resourceService.length > 0) {
                        resourceName = resourceService[0];
                    }
                    if (resourceService.length > 1) {
                        serviceName = resourceService[1];
                    }
                }
            }
            if (resourceName == null) {
                //TODO: log message and fill missing attribute details 
                statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
                evaluationFailed = true;
            }
            if (serviceName == null) {
                //TODO: log message and fill missing attribute details
                throw new SAML2Exception(XACMLSDKUtils.xacmlResourceBundle.getString("missing_attribute"));
            }
        }
        if (serviceName != null) {
            //get native action name
            if (serviceName != null) {
                actionName = actionMapper.mapToNativeAction(xacmlRequest.getAction(), serviceName);
            }
            if (actionName == null) {
                //TODO: log message and fill missing attribute details
                statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
                evaluationFailed = true;
            }
        }
    //get environment map
    /*
            environment = environmentMapper.mapToNativeEnvironment(
                    xacmlRequest.getEnvironment(), 
                    xacmlRequest.getSubjects());
            */
    } catch (XACMLException xe) {
        statusCodeValue = XACMLConstants.STATUS_CODE_MISSING_ATTRIBUTE;
        evaluationFailed = true;
        if (XACMLSDKUtils.debug.warningEnabled()) {
            XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", xe);
        }
    }
    //get native policy deicison using native policy evaluator
    if (!evaluationFailed) {
        try {
            PolicyEvaluator pe = new PolicyEvaluator(serviceName);
            booleanDecision = pe.isAllowed(ssoToken, resourceName, actionName, environment);
        } catch (SSOException ssoe) {
            if (XACMLSDKUtils.debug.warningEnabled()) {
                XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", ssoe);
            }
            evaluationFailed = true;
        } catch (PolicyException pe) {
            if (XACMLSDKUtils.debug.warningEnabled()) {
                XACMLSDKUtils.debug.warning("XACMLAuthzDecisionQueryHandler.handleQuery()," + "caught exception", pe);
            }
            evaluationFailed = true;
        }
    }
    //decision: Indeterminate, Deny, Permit, NotApplicable
    //status code: missing_attribute, syntax_error, processing_error, ok
    Decision decision = ContextFactory.getInstance().createDecision();
    Status status = ContextFactory.getInstance().createStatus();
    StatusCode code = ContextFactory.getInstance().createStatusCode();
    StatusMessage message = ContextFactory.getInstance().createStatusMessage();
    StatusDetail detail = ContextFactory.getInstance().createStatusDetail();
    detail.getElement().insertBefore(detail.getElement().cloneNode(true), null);
    if (evaluationFailed) {
        decision.setValue(XACMLConstants.INDETERMINATE);
        if (statusCodeValue == null) {
            statusCodeValue = XACMLConstants.STATUS_CODE_PROCESSING_ERROR;
        }
        code.setValue(statusCodeValue);
        //TODO: i18n
        message.setValue("processing_error");
    } else if (booleanDecision) {
        decision.setValue(XACMLConstants.PERMIT);
        code.setValue(XACMLConstants.STATUS_CODE_OK);
        //TODO: i18n
        message.setValue("ok");
    } else {
        decision.setValue(XACMLConstants.DENY);
        code.setValue(XACMLConstants.STATUS_CODE_OK);
        //TODO: i18n
        message.setValue("ok");
    }
    Result result = ContextFactory.getInstance().createResult();
    String resourceId = resourceName;
    List resources = xacmlRequest.getResources();
    Resource resource = null;
    if (!resources.isEmpty()) {
        //We deal with only one resource for now
        resource = (Resource) resources.get(0);
        if (resource != null) {
            List attributes = resource.getAttributes();
            if (attributes != null) {
                for (int count = 0; count < attributes.size(); count++) {
                    Attribute attr = (Attribute) attributes.get(count);
                    if (attr != null) {
                        URI tmpURI = attr.getAttributeId();
                        if (tmpURI.toString().equals(XACMLConstants.RESOURCE_ID)) {
                            Element element = (Element) attr.getAttributeValues().get(0);
                            resourceId = XMLUtils.getElementValue(element);
                            break;
                        }
                    }
                }
            }
        }
    }
    result.setResourceId(resourceId);
    result.setDecision(decision);
    status.setStatusCode(code);
    status.setStatusMessage(message);
    status.setStatusDetail(detail);
    result.setStatus(status);
    Response response = ContextFactory.getInstance().createResponse();
    response.addResult(result);
    XACMLAuthzDecisionStatement statement = ContextFactory.getInstance().createXACMLAuthzDecisionStatement();
    statement.setResponse(response);
    if (returnContext) {
        statement.setRequest(xacmlRequest);
    }
    com.sun.identity.saml2.protocol.Response samlpResponse = createSamlpResponse(statement, status.getStatusCode().getValue());
    if (XACMLSDKUtils.debug.messageEnabled()) {
        XACMLSDKUtils.debug.message("XACMLAuthzDecisionQueryHandler.handleQuery(), returning" + ":samlResponse=\n" + samlpResponse.toXMLString(true, true));
    }
    return samlpResponse;
}
Also used : SSOToken(com.iplanet.sso.SSOToken) Attribute(com.sun.identity.xacml.context.Attribute) Element(org.w3c.dom.Element) SSOException(com.iplanet.sso.SSOException) StatusCode(com.sun.identity.xacml.context.StatusCode) URI(java.net.URI) Result(com.sun.identity.xacml.context.Result) ResourceResult(com.sun.identity.policy.ResourceResult) ActionMapper(com.sun.identity.xacml.spi.ActionMapper) XACMLAuthzDecisionStatement(com.sun.identity.xacml.saml2.XACMLAuthzDecisionStatement) PolicyEvaluator(com.sun.identity.policy.PolicyEvaluator) SubjectMapper(com.sun.identity.xacml.spi.SubjectMapper) PolicyException(com.sun.identity.policy.PolicyException) ResourceMapper(com.sun.identity.xacml.spi.ResourceMapper) ArrayList(java.util.ArrayList) List(java.util.List) Status(com.sun.identity.xacml.context.Status) Request(com.sun.identity.xacml.context.Request) Resource(com.sun.identity.xacml.context.Resource) EnvironmentMapper(com.sun.identity.xacml.spi.EnvironmentMapper) Decision(com.sun.identity.xacml.context.Decision) XACMLException(com.sun.identity.xacml.common.XACMLException) StatusMessage(com.sun.identity.xacml.context.StatusMessage) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Response(com.sun.identity.xacml.context.Response) ResultMapper(com.sun.identity.xacml.spi.ResultMapper) StatusDetail(com.sun.identity.xacml.context.StatusDetail) XACMLAuthzDecisionQuery(com.sun.identity.xacml.saml2.XACMLAuthzDecisionQuery) Map(java.util.Map)

Example 13 with Status

use of com.sun.identity.saml2.protocol.Status in project OpenAM by OpenRock.

the class DefaultFedletAdapter method doFedletSLO.

/**
     * Invokes after Fedlet receives SLO request from IDP. It does the work
     * of logout the user.
     * @param request servlet request
     * @param response servlet response
     * @param hostedEntityID entity ID for the fedlet
     * @param idpEntityID entity id for the IDP to which the request is
     *          received from.
     * @param siList List of SessionIndex whose session to be logged out
     * @param nameIDValue nameID value whose session to be logged out
     * @param binding Single Logout binding used,
     *      one of following values:
     *          <code>SAML2Constants.SOAP</code>,
     *          <code>SAML2Constants.HTTP_POST</code>,
     *          <code>SAML2Constants.HTTP_REDIRECT</code>
     * @return <code>true</code> if user is logged out successfully;
     *          <code>false</code> otherwise.
     * @exception SAML2Exception if user want to fail the process.
     */
public boolean doFedletSLO(HttpServletRequest request, HttpServletResponse response, LogoutRequest logoutReq, String hostedEntityID, String idpEntityID, List siList, String nameIDValue, String binding) throws SAML2Exception {
    boolean status = true;
    String method = "DefaultFedletAdapter:doFedletSLO:";
    try {
        if (logoutUrl == null) {
            BaseConfigType spConfig = SAML2Utils.getSAML2MetaManager().getSPSSOConfig("/", hostedEntityID);
            List appLogoutURL = (List) SAML2MetaUtils.getAttributes(spConfig).get(SAML2Constants.APP_LOGOUT_URL);
            if ((appLogoutURL != null) && !appLogoutURL.isEmpty()) {
                logoutUrl = (String) appLogoutURL.get(0);
            }
        }
        if (logoutUrl == null) {
            String deployuri = request.getRequestURI();
            int slashLoc = deployuri.indexOf("/", 1);
            if (slashLoc != -1) {
                deployuri = deployuri.substring(0, slashLoc);
            }
            if (deployuri != null) {
                String url = request.getRequestURL().toString();
                int loc = url.indexOf(deployuri + "/");
                if (loc != -1) {
                    logoutUrl = url.substring(0, loc + deployuri.length()) + "/logout";
                }
            }
        }
        if (logoutUrl == null) {
            return status;
        }
        URL url = new URL(logoutUrl);
        HttpURLConnection conn = HttpURLConnectionManager.getConnection(url);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setFollowRedirects(false);
        conn.setInstanceFollowRedirects(false);
        // replay cookies
        String strCookies = SAML2Utils.getCookiesString(request);
        if (strCookies != null) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "Sending cookies : " + strCookies);
            }
            conn.setRequestProperty("Cookie", strCookies);
        }
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("IDP", URLEncDec.encode(idpEntityID));
        conn.setRequestProperty("SP", URLEncDec.encode(hostedEntityID));
        conn.setRequestProperty("NameIDValue", URLEncDec.encode(nameIDValue));
        if (siList != null && !siList.isEmpty()) {
            Iterator iter = siList.iterator();
            StringBuffer siValue = new StringBuffer();
            siValue.append((String) iter.next());
            while (iter.hasNext()) {
                siValue.append(",").append((String) iter.next());
            }
            conn.setRequestProperty("SessionIndex", URLEncDec.encode(siValue.toString()));
        }
        conn.setRequestProperty("Binding", binding);
        OutputStream outputStream = conn.getOutputStream();
        // Write the request to the HTTP server.
        outputStream.write("".getBytes());
        outputStream.flush();
        outputStream.close();
        // Check response code
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(method + "Response code OK");
            }
            status = true;
        } else {
            SAML2Utils.debug.error(method + "Response code NOT OK: " + conn.getResponseCode());
            status = false;
        }
    } catch (Exception e) {
        status = false;
    }
    return status;
}
Also used : BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) HttpURLConnection(java.net.HttpURLConnection) OutputStream(java.io.OutputStream) Iterator(java.util.Iterator) List(java.util.List) URL(java.net.URL) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 14 with Status

use of com.sun.identity.saml2.protocol.Status in project OpenAM by OpenRock.

the class SPSingleLogout method isNameNotFound.

static boolean isNameNotFound(LogoutResponse logoutRes) {
    Status status = logoutRes.getStatus();
    String statusMessage = status.getStatusMessage();
    return (status.getStatusCode().getValue().equals(SAML2Constants.RESPONDER) && statusMessage != null && statusMessage.equals(SAML2Utils.bundle.getString("invalid_name_identifier")));
}
Also used : Status(com.sun.identity.saml2.protocol.Status)

Example 15 with Status

use of com.sun.identity.saml2.protocol.Status 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)27 Status (com.sun.identity.saml2.protocol.Status)16 List (java.util.List)16 ArrayList (java.util.ArrayList)11 Date (java.util.Date)11 Element (org.w3c.dom.Element)11 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)10 Issuer (com.sun.identity.saml2.assertion.Issuer)9 IOException (java.io.IOException)9 SessionException (com.sun.identity.plugin.session.SessionException)8 ProtocolFactory (com.sun.identity.saml2.protocol.ProtocolFactory)8 Iterator (java.util.Iterator)8 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)8 Response (com.sun.identity.saml2.protocol.Response)7 StatusCode (com.sun.identity.saml2.protocol.StatusCode)7 HttpServletResponse (javax.servlet.http.HttpServletResponse)7 Assertion (com.sun.identity.saml2.assertion.Assertion)6 LogoutResponse (com.sun.identity.saml2.protocol.LogoutResponse)6 Node (org.w3c.dom.Node)6 NodeList (org.w3c.dom.NodeList)6