Search in sources :

Example 81 with SessionException

use of com.sun.identity.plugin.session.SessionException in project OpenAM by OpenRock.

the class AssertionManagerImpl method getAssertionArtifacts.

public Set getAssertionArtifacts(String ssoToken) throws SAMLException {
    checkInitialization();
    try {
        SessionProvider sessionProvider = SessionManager.getProvider();
        Object token = sessionProvider.getSession(ssoToken);
        return (assertionManager.getAssertionArtifacts(token));
    } catch (SessionException ssoe) {
        if (SAMLUtils.debug.messageEnabled()) {
            SAMLUtils.debug.message("AssertionManagerImpl:getAssertionArtifacts: " + ssoe);
        }
        throw (new SAMLException(ssoe.getMessage()));
    }
}
Also used : SessionException(com.sun.identity.plugin.session.SessionException) SAMLException(com.sun.identity.saml.common.SAMLException) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Example 82 with SessionException

use of com.sun.identity.plugin.session.SessionException in project OpenAM by OpenRock.

the class AssertionManagerImpl method createAssertion2.

public String createAssertion2(String ssoToken, List attributes) throws SAMLException {
    checkInitialization();
    Object token = null;
    try {
        SessionProvider sessionProvider = SessionManager.getProvider();
        token = sessionProvider.getSession(ssoToken);
    } catch (SessionException ssoe) {
        if (SAMLUtils.debug.messageEnabled()) {
            SAMLUtils.debug.message("AssertionManagerImpl:createAssertion(SSO + attrs) " + ssoe);
        }
        throw (new SAMLException(ssoe.getMessage()));
    }
    LinkedList ll = new LinkedList();
    for (Iterator iter = attributes.iterator(); iter.hasNext(); ) {
        ll.add(new Attribute(XMLUtils.toDOMDocument((String) iter.next(), SAMLUtils.debug).getDocumentElement()));
    }
    Assertion a = assertionManager.createAssertion(token, ll);
    return (a.toString(true, true));
}
Also used : Attribute(com.sun.identity.saml.assertion.Attribute) Assertion(com.sun.identity.saml.assertion.Assertion) SessionException(com.sun.identity.plugin.session.SessionException) SAMLException(com.sun.identity.saml.common.SAMLException) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Example 83 with SessionException

use of com.sun.identity.plugin.session.SessionException in project OpenAM by OpenRock.

the class SAML2Utils method postToAppLogout.

/**
     * Processes logout for external application. This will do a back channel
     * HTTP POST to the external application logout URL with all the cookies
     * and selected session property as HTTP header.
     *
     * @param request      HttpServletRequest
     * @param appLogoutURL external application logout URL
     * @param session      session object of the user
     */
public static void postToAppLogout(HttpServletRequest request, String appLogoutURL, Object session) {
    String method = "SAML2Utils.postToAppLogout: ";
    try {
        if ((appLogoutURL == null) || (appLogoutURL.length() == 0)) {
            return;
        }
        // actual application logout URL without the session 
        // property query parameter
        String logoutURL = appLogoutURL;
        // name of the session property
        String sessProp = null;
        // find out session property name from the URL
        int pos = appLogoutURL.indexOf(SAML2Constants.APP_SESSION_PROPERTY + "=");
        if (pos != -1) {
            int endPos = appLogoutURL.indexOf("&", pos);
            if (endPos != -1) {
                sessProp = appLogoutURL.substring(pos + SAML2Constants.APP_SESSION_PROPERTY.length() + 1, endPos);
                logoutURL = appLogoutURL.substring(0, pos) + appLogoutURL.substring(endPos + 1);
            } else {
                sessProp = appLogoutURL.substring(pos + SAML2Constants.APP_SESSION_PROPERTY.length() + 1);
                logoutURL = appLogoutURL.substring(0, pos - 1);
            }
        }
        if (debug.messageEnabled()) {
            debug.message(method + "appLogoutURL=" + appLogoutURL + ", real logoutURL=" + logoutURL + ", session property name: " + sessProp);
        }
        URL url = new URL(logoutURL);
        HttpURLConnection conn = HttpURLConnectionManager.getConnection(url);
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        HttpURLConnection.setFollowRedirects(false);
        conn.setInstanceFollowRedirects(false);
        // replay cookies
        String strCookies = getCookiesString(request);
        if (strCookies != null) {
            if (debug.messageEnabled()) {
                debug.message(method + "Sending cookies : " + strCookies);
            }
            conn.setRequestProperty("Cookie", strCookies);
        }
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        // set header & content 
        StringBuffer buffer = new StringBuffer();
        buffer.append("");
        if ((sessProp != null) && (session != null)) {
            String[] values = SessionManager.getProvider().getProperty(session, sessProp);
            if ((values != null) && (values.length != 0)) {
                int i = 0;
                while (true) {
                    conn.setRequestProperty(URLEncDec.encode(sessProp), URLEncDec.encode(values[i]));
                    buffer.append(URLEncDec.encode(sessProp)).append('=');
                    buffer.append(URLEncDec.encode(values[i++]));
                    if (i != values.length) {
                        buffer.append('&');
                    } else {
                        break;
                    }
                }
            }
        }
        if (debug.messageEnabled()) {
            debug.message(method + "Sending content: " + buffer.toString());
        }
        OutputStream outputStream = conn.getOutputStream();
        // Write the request to the HTTP server.
        outputStream.write(buffer.toString().getBytes());
        outputStream.flush();
        outputStream.close();
        // Check response code
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            if (debug.messageEnabled()) {
                debug.message(method + "Response code OK");
            }
        } else {
            debug.error(method + "Response code NOT OK: " + conn.getResponseCode());
        }
    } catch (SessionException ex) {
        debug.error(method + " post to external app failed.", ex);
    } catch (IOException ex) {
        debug.error(method + " post to external app failed.", ex);
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DeflaterOutputStream(java.util.zip.DeflaterOutputStream) OutputStream(java.io.OutputStream) SessionException(com.sun.identity.plugin.session.SessionException) IOException(java.io.IOException) URL(java.net.URL)

Example 84 with SessionException

use of com.sun.identity.plugin.session.SessionException in project OpenAM by OpenRock.

the class DoManageNameID method doMNIBySOAP.

private static boolean doMNIBySOAP(ManageNameIDRequest mniRequest, String mniURL, String metaAlias, String hostRole, HttpServletRequest request, HttpServletResponse response) throws SAML2Exception {
    String method = "doMNIBySOAP: ";
    boolean success = false;
    String mniRequestXMLString = mniRequest.toXMLString(true, true);
    if (debug.messageEnabled()) {
        debug.message(method + "MNIRequestXMLString : " + mniRequestXMLString);
        debug.message(method + "MNIRedirectURL : " + mniURL);
    }
    SOAPMessage resMsg = null;
    try {
        resMsg = SOAPCommunicator.getInstance().sendSOAPMessage(mniRequestXMLString, mniURL, true);
    } catch (SOAPException se) {
        debug.error(SAML2Utils.bundle.getString("invalidSOAPMessge"), se);
        return false;
    }
    Element mniRespElem = SOAPCommunicator.getInstance().getSamlpElement(resMsg, "ManageNameIDResponse");
    ManageNameIDResponse mniResponse = mniResponse = pf.createManageNameIDResponse(mniRespElem);
    if (debug.messageEnabled()) {
        if (mniResponse != null) {
            debug.message(method + "ManageNameIDResponse without " + "SOAP envelope:\n" + mniResponse.toXMLString());
        } else {
            debug.message(method + "ManageNameIDResponse is null ");
        }
    }
    if (mniResponse != null) {
        try {
            String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
            String hostEntityID = metaManager.getEntityByMetaAlias(metaAlias);
            String remoteEntityID = mniResponse.getIssuer().getValue();
            Issuer resIssuer = mniResponse.getIssuer();
            String requestId = mniResponse.getInResponseTo();
            SAML2Utils.verifyResponseIssuer(realm, hostEntityID, resIssuer, requestId);
            boolean validSign = verifyMNIResponse(mniResponse, realm, remoteEntityID, hostEntityID, hostRole, mniResponse.getDestination());
            if (!validSign) {
                logError("invalidSignInResponse", LogUtil.CANNOT_INSTANTIATE_MNI_RESPONSE, null);
                throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSignInResponse"));
            }
            StringBuffer mniUserId = new StringBuffer();
            success = checkMNIResponse(mniResponse, realm, hostEntityID, hostRole, mniUserId);
            if (success && hostRole.equals(SAML2Constants.SP_ROLE)) {
                // invoke SPAdapter for termination success, SP initied SOAP
                postTerminationSuccess(hostEntityID, realm, request, response, mniUserId.toString(), mniRequest, mniResponse, SAML2Constants.SOAP);
            }
        } catch (SessionException e) {
            debug.error(SAML2Utils.bundle.getString("invalidSSOToken"), e);
            throw new SAML2Exception(e.toString());
        }
    }
    if (debug.messageEnabled()) {
        debug.message(method + "Request success : " + success);
    }
    return success;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Issuer(com.sun.identity.saml2.assertion.Issuer) SOAPException(javax.xml.soap.SOAPException) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) ManageNameIDServiceElement(com.sun.identity.saml2.jaxb.metadata.ManageNameIDServiceElement) Element(org.w3c.dom.Element) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement) SessionException(com.sun.identity.plugin.session.SessionException) SOAPMessage(javax.xml.soap.SOAPMessage) ManageNameIDResponse(com.sun.identity.saml2.protocol.ManageNameIDResponse)

Example 85 with SessionException

use of com.sun.identity.plugin.session.SessionException in project OpenAM by OpenRock.

the class DoManageNameID method checkMNIResponse.

private static boolean checkMNIResponse(ManageNameIDResponse mniResponse, String realm, String hostEntityID, String hostRole, StringBuffer mniUserId) throws SAML2Exception, SessionException {
    boolean success = false;
    String remoteEntityID = mniResponse.getIssuer().getValue();
    String requestID = mniResponse.getInResponseTo();
    ManageNameIDRequestInfo reqInfo = getMNIRequestInfo(requestID, hostRole);
    if (reqInfo == null) {
        logError("invalidInResponseToInResponse", LogUtil.INVALID_MNI_RESPONSE, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidInResponseToInResponse"));
    }
    String retCode = mniResponse.getStatus().getStatusCode().getValue();
    if (retCode.equalsIgnoreCase(SAML2Constants.SUCCESS)) {
        Object session = reqInfo.getSession();
        if (session == null) {
            logError("nullSSOToken", LogUtil.INVALID_SSOTOKEN, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("nullSSOToken"));
        }
        String userID = sessionProvider.getPrincipalName(session);
        mniUserId.append(userID);
        ManageNameIDRequest origMniReq = reqInfo.getManageNameIDRequest();
        NameID oldNameID = origMniReq.getNameID();
        List spFedSessions = null;
        NameIDInfo oldNameIDInfo = getNameIDInfo(userID, hostEntityID, remoteEntityID, hostRole, realm, oldNameID.getSPNameQualifier(), true);
        if (oldNameIDInfo == null) {
            debug.error("DoManageNameID.checkMNIResponse: NameIDInfo " + "not found.");
            return false;
        }
        // Terminate
        if (hostRole.equalsIgnoreCase(SAML2Constants.SP_ROLE)) {
            String infoKeyStr = oldNameIDInfo.getNameIDInfoKey().toValueString();
            spFedSessions = (List) SPCache.fedSessionListsByNameIDInfoKey.remove(infoKeyStr);
            removeInfoKeyFromSession(session, infoKeyStr);
            if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
            }
        } else {
            removeIDPFedSession(remoteEntityID, oldNameID.getValue());
        }
        if (!AccountUtils.removeAccountFederation(oldNameIDInfo, userID)) {
            // log termination failure
            logError("unableToTerminate", LogUtil.UNABLE_TO_TERMINATE, userID);
            return false;
        }
        if (origMniReq.getTerminate()) {
            // log termination success
            logAccess("requestSuccess", LogUtil.SUCCESS_FED_TERMINATION, userID);
            return true;
        }
        // newID case
        String newIDValue = origMniReq.getNewID().getValue();
        boolean isAffiliation = oldNameIDInfo.isAffiliation();
        String spNameQualifier = oldNameID.getSPNameQualifier();
        if (hostRole.equalsIgnoreCase(SAML2Constants.SP_ROLE)) {
            NameID newNameID = AssertionFactory.getInstance().createNameID();
            newNameID.setValue(oldNameID.getValue());
            newNameID.setFormat(oldNameID.getFormat());
            newNameID.setSPProvidedID(newIDValue);
            newNameID.setSPNameQualifier(spNameQualifier);
            newNameID.setNameQualifier(oldNameID.getNameQualifier());
            NameIDInfo newNameIDInfo = new NameIDInfo((isAffiliation ? spNameQualifier : hostEntityID), remoteEntityID, newNameID, hostRole, isAffiliation);
            String newInfoKeyStr = newNameIDInfo.getNameIDInfoKey().toValueString();
            if (spFedSessions != null) {
                SPCache.fedSessionListsByNameIDInfoKey.put(newInfoKeyStr, spFedSessions);
                if ((agent != null) && agent.isRunning() && (saml2Svc != null)) {
                    saml2Svc.setFedSessionCount((long) SPCache.fedSessionListsByNameIDInfoKey.size());
                }
            }
            AccountUtils.setAccountFederation(newNameIDInfo, userID);
            try {
                String infoKeyAttribute = AccountUtils.getNameIDInfoKeyAttribute();
                String[] fromToken = sessionProvider.getProperty(session, infoKeyAttribute);
                if ((fromToken == null) || (fromToken.length == 0) || (fromToken[0] == null) || (fromToken[0].length() == 0)) {
                    String[] values = { newInfoKeyStr };
                    sessionProvider.setProperty(session, infoKeyAttribute, values);
                } else {
                    if (fromToken[0].indexOf(newInfoKeyStr) == -1) {
                        String[] values = { fromToken[0] + SAML2Constants.SECOND_DELIM + newInfoKeyStr };
                        sessionProvider.setProperty(session, infoKeyAttribute, values);
                    }
                }
            } catch (Exception e) {
                debug.message("DoManageNameID.checkMNIResponse:", e);
            }
        } else if (hostRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
            NameID newNameID = AssertionFactory.getInstance().createNameID();
            newNameID.setValue(newIDValue);
            newNameID.setFormat(oldNameID.getFormat());
            newNameID.setSPProvidedID(oldNameID.getSPProvidedID());
            newNameID.setSPNameQualifier(spNameQualifier);
            newNameID.setNameQualifier(hostEntityID);
            NameIDInfo newNameIDInfo = new NameIDInfo(hostEntityID, (isAffiliation ? spNameQualifier : remoteEntityID), newNameID, SAML2Constants.IDP_ROLE, isAffiliation);
            AccountUtils.setAccountFederation(newNameIDInfo, userID);
            NameIDandSPpair pair = new NameIDandSPpair(newNameID, remoteEntityID);
            IDPSession idpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(sessionProvider.getSessionID(session));
            if (idpSession != null) {
                synchronized (IDPCache.idpSessionsByIndices) {
                    List list = (List) idpSession.getNameIDandSPpairs();
                    list.add(pair);
                }
            }
        }
        // log manage name id success
        logAccess("newNameIDSuccess", LogUtil.SUCCESS_NEW_NAMEID, userID);
        success = true;
    } else {
        logError("mniFailed", LogUtil.INVALID_MNI_RESPONSE, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("mniFailed"));
    }
    return success;
}
Also used : NameIDInfo(com.sun.identity.saml2.common.NameIDInfo) ManageNameIDRequest(com.sun.identity.saml2.protocol.ManageNameIDRequest) NameID(com.sun.identity.saml2.assertion.NameID) ServletException(javax.servlet.ServletException) SOAPException(javax.xml.soap.SOAPException) SessionException(com.sun.identity.plugin.session.SessionException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) List(java.util.List)

Aggregations

SessionException (com.sun.identity.plugin.session.SessionException)121 SessionProvider (com.sun.identity.plugin.session.SessionProvider)55 List (java.util.List)40 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)35 IOException (java.io.IOException)28 ArrayList (java.util.ArrayList)28 Set (java.util.Set)24 SAMLException (com.sun.identity.saml.common.SAMLException)23 Iterator (java.util.Iterator)20 HashMap (java.util.HashMap)18 HashSet (java.util.HashSet)18 Map (java.util.Map)18 FSSession (com.sun.identity.federation.services.FSSession)17 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)17 FSSessionManager (com.sun.identity.federation.services.FSSessionManager)15 FSException (com.sun.identity.federation.common.FSException)13 IDFFMetaException (com.sun.identity.federation.meta.IDFFMetaException)12 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)11 ServletException (javax.servlet.ServletException)10 DataStoreProviderException (com.sun.identity.plugin.datastore.DataStoreProviderException)9