Search in sources :

Example 61 with SessionException

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

the class IDPSSOUtil method sendResponseToACS.

/**
     * Sends <code>Response</code> containing an <code>Assertion</code>
     * back to the requesting service provider
     *
     * @param request              the <code>HttpServletRequest</code> object
     * @param response             the <code>HttpServletResponse</code> object
     * @param out                  the print writer for writing out presentation
     * @param session              user session
     * @param authnReq             the <code>AuthnRequest</code> object
     * @param spEntityID           the entity id of the service provider
     * @param idpEntityID          the entity id of the identity provider
     * @param idpMetaAlias         the meta alias of the identity provider
     * @param realm                the realm
     * @param nameIDFormat         the <code>NameIDFormat</code>
     * @param relayState           the relay state
     * @param matchingAuthnContext the <code>AuthnContext</code> used to find
     *                             authentication type and scheme.
     */
public static void sendResponseToACS(HttpServletRequest request, HttpServletResponse response, PrintWriter out, Object session, AuthnRequest authnReq, String spEntityID, String idpEntityID, String idpMetaAlias, String realm, String nameIDFormat, String relayState, AuthnContext matchingAuthnContext) throws SAML2Exception {
    StringBuffer returnedBinding = new StringBuffer();
    String acsURL = IDPSSOUtil.getACSurl(spEntityID, realm, authnReq, request, returnedBinding);
    String acsBinding = returnedBinding.toString();
    if ((acsURL == null) || (acsURL.trim().length() == 0)) {
        SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " no ACS URL found.");
        String[] data = { idpMetaAlias };
        LogUtil.error(Level.INFO, LogUtil.NO_ACS_URL, data, session);
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableTofindACSURL"));
    }
    if ((acsBinding == null) || (acsBinding.trim().length() == 0)) {
        SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " no return binding found.");
        String[] data = { idpMetaAlias };
        LogUtil.error(Level.INFO, LogUtil.NO_RETURN_BINDING, data, session);
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableTofindBinding"));
    }
    String affiliationID = request.getParameter(SAML2Constants.AFFILIATION_ID);
    //check first if there is already an existing sessionindex associated with this SSOToken, if there is, then
    //we need to redirect the request internally to the holder of the idpsession.
    //The remoteServiceURL will be null if there is no sessionindex for this SSOToken, or there is, but it's
    //local. If the remoteServiceURL is not null, we can start to send the request to the original server.
    String remoteServiceURL = SAML2Utils.getRemoteServiceURL(getSessionIndex(session));
    if (remoteServiceURL != null) {
        remoteServiceURL += SAML2Utils.removeDeployUri(request.getRequestURI()) + "?" + request.getQueryString();
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("SessionIndex for this SSOToken is not local, forwarding the request to: " + remoteServiceURL);
        }
        String redirectUrl = null;
        String outputData = null;
        String responseCode = null;
        HashMap<String, String> remoteRequestData = SAML2Utils.sendRequestToOrigServer(request, response, remoteServiceURL);
        if (remoteRequestData != null && !remoteRequestData.isEmpty()) {
            redirectUrl = remoteRequestData.get(SAML2Constants.AM_REDIRECT_URL);
            outputData = remoteRequestData.get(SAML2Constants.OUTPUT_DATA);
            responseCode = remoteRequestData.get(SAML2Constants.RESPONSE_CODE);
        }
        try {
            if (redirectUrl != null && !redirectUrl.isEmpty()) {
                response.sendRedirect(redirectUrl);
            } else {
                if (responseCode != null) {
                    response.setStatus(Integer.valueOf(responseCode));
                }
                // no redirect, perhaps an error page, return the content
                if (outputData != null && !outputData.isEmpty()) {
                    SAML2Utils.debug.message("Printing the forwarded response");
                    response.setContentType("text/html; charset=UTF-8");
                    out.println(outputData);
                    return;
                }
            }
        } catch (IOException ioe) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS() error in Request Routing", ioe);
            }
        }
        return;
    }
    //end of request proxy
    // generate a response for the authn request
    Response res = getResponse(request, session, authnReq, spEntityID, idpEntityID, idpMetaAlias, realm, nameIDFormat, acsURL, affiliationID, matchingAuthnContext);
    if (res == null) {
        SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " response is null");
        String errorMsg = SAML2Utils.bundle.getString("UnableToCreateAssertion");
        if (authnReq == null) {
            //idp initiated case, will not send error response to sp
            throw new SAML2Exception(errorMsg);
        }
        res = SAML2Utils.getErrorResponse(authnReq, SAML2Constants.RESPONDER, null, errorMsg, idpEntityID);
    } else {
        try {
            String[] values = { idpMetaAlias };
            sessionProvider.setProperty(session, SAML2Constants.IDP_META_ALIAS, values);
        } catch (SessionException e) {
            SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " error setting idpMetaAlias into the session: ", e);
        }
    }
    if (res != null) {
        // call multi-federation protocol to set the protocol
        MultiProtocolUtils.addFederationProtocol(session, SingleLogoutManager.SAML2);
        // check if the COT cookie needs to be set
        if (setCOTCookie(request, response, acsBinding, spEntityID, idpEntityID, idpMetaAlias, realm, relayState, acsURL, res, session)) {
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS:" + " Redirected to set COT cookie.");
            }
            return;
        }
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS:" + " Doesn't set COT cookie.");
            SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS:" + " Response is:  " + res.toXMLString());
        }
        try {
            SAML2Utils.debug.message("IDPSSOUtil.sendResponseToACS: Invoking the IDP Adapter");
            SAML2IdentityProviderAdapter idpAdapter = IDPSSOUtil.getIDPAdapterClass(realm, idpEntityID);
            if (idpAdapter != null) {
                idpAdapter.preSignResponse(authnReq, res, idpEntityID, realm, request, session, relayState);
            }
        } catch (SAML2Exception se) {
            SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS: There was a problem when invoking the " + "preSendResponse of the IDP Adapter: ", se);
        }
        sendResponse(request, response, out, acsBinding, spEntityID, idpEntityID, idpMetaAlias, realm, relayState, acsURL, res, session);
    } else {
        SAML2Utils.debug.error("IDPSSOUtil.sendResponseToACS:" + " error response is null");
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableToCreateErrorResponse"));
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ECPResponse(com.sun.identity.saml2.ecp.ECPResponse) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) SessionException(com.sun.identity.plugin.session.SessionException) IOException(java.io.IOException) SAML2IdentityProviderAdapter(com.sun.identity.saml2.plugins.SAML2IdentityProviderAdapter)

Example 62 with SessionException

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

the class IDPProxyUtil method getSessionPartners.

public static List getSessionPartners(HttpServletRequest request) {
    try {
        Object tmpsession = sessionProvider.getSession(request);
        String tokenID = sessionProvider.getSessionID(tmpsession);
        IDPSession idpSession = null;
        if (tokenID != null && !tokenID.equals("")) {
            idpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(tokenID);
        }
        List partners = null;
        if (idpSession != null) {
            partners = idpSession.getSessionPartners();
        }
        if (SAML2Utils.debug.messageEnabled()) {
            if (partners != null && !partners.isEmpty()) {
                Iterator iter = partners.iterator();
                while (iter.hasNext()) {
                    SAML2SessionPartner partner = (SAML2SessionPartner) iter.next();
                    if (SAML2Utils.debug.messageEnabled()) {
                        SAML2Utils.debug.message("SESSION PARTNER's Provider ID:  " + partner.getPartner());
                    }
                }
            }
        }
        return partners;
    } catch (SessionException se) {
        return null;
    }
}
Also used : Iterator(java.util.Iterator) SessionException(com.sun.identity.plugin.session.SessionException) List(java.util.List) IDPList(com.sun.identity.saml2.protocol.IDPList) ArrayList(java.util.ArrayList)

Example 63 with SessionException

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

the class IDPProxyUtil method sendProxyLogoutRequest.

public static void sendProxyLogoutRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out, LogoutRequest logoutReq, List partners, String binding, String relayState) {
    try {
        Object tmpsession = sessionProvider.getSession(request);
        String tokenID = sessionProvider.getSessionID(tmpsession);
        IDPSession idpSession = null;
        if (tokenID != null && !tokenID.equals("")) {
            idpSession = (IDPSession) IDPCache.idpSessionsBySessionID.get(tokenID);
        }
        Iterator iter = partners.iterator();
        SAML2SessionPartner partner = (SAML2SessionPartner) iter.next();
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("CURRENT PARTNER's provider ID: " + partner.getPartner());
            SAML2Utils.debug.message("Starting IDP proxy logout.");
        }
        String metaAlias = SAML2MetaUtils.getMetaAliasByUri(request.getRequestURI());
        String realm = SAML2Utils.getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
        String party = partner.getPartner();
        if (idpSession != null) {
            idpSession.removeSessionPartner(party);
            IDPCache.idpSessionsBySessionID.remove(tokenID);
            initiateSPLogoutRequest(request, response, out, party, metaAlias, realm, logoutReq, null, idpSession, binding, relayState);
        }
    } catch (SessionException se) {
        SAML2Utils.debug.error("sendProxyLogoutRequest: ", se);
    }
}
Also used : Iterator(java.util.Iterator) SessionException(com.sun.identity.plugin.session.SessionException)

Example 64 with SessionException

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

the class DoManageNameID method initiateManageNameIDRequest.

/**
     * Parses the request parameters and builds the ManageNameID
     * Request to sent to remote Entity.
     *
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     * @param metaAlias entityID of hosted entity.
     * @param remoteEntityID entityID of remote entity.
     * @param paramsMap Map of all other parameters.
     * @throws SAML2Exception if error initiating request to remote entity.
     */
public static void initiateManageNameIDRequest(HttpServletRequest request, HttpServletResponse response, String metaAlias, String remoteEntityID, Map paramsMap) throws SAML2Exception {
    String method = "DoManageNameID.initiateManageNameIDRequest: ";
    if (metaManager == null) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorMetaManager"));
    }
    if (metaAlias == null) {
        logError("MetaAliasNotFound", LogUtil.MISSING_META_ALIAS, metaAlias);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullEntityID"));
    }
    if (remoteEntityID == null) {
        logError("nullRemoteEntityID", LogUtil.MISSING_ENTITY, remoteEntityID);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullRemoteEntityID"));
    }
    Object session = null;
    try {
        session = SessionManager.getProvider().getSession(request);
    } catch (SessionException se) {
        if (debug.messageEnabled()) {
            debug.message(method, se);
        }
    }
    String realm = SAML2MetaUtils.getRealmByMetaAlias(metaAlias);
    String hostEntityID = metaManager.getEntityByMetaAlias(metaAlias);
    String hostEntityRole = SAML2Utils.getHostEntityRole(paramsMap);
    if (session == null) {
        if (debug.messageEnabled()) {
            debug.message(method + "Session is missing." + "redirect to the authentication service");
        }
        // redirect to the authentication service
        try {
            SAML2Utils.redirectAuthentication(request, response, realm, hostEntityID, hostEntityRole);
        } catch (IOException ioe) {
            logError("UnableToRedirectToAuth", LogUtil.REDIRECT_TO_AUTH, null);
            throw new SAML2Exception(ioe.toString());
        }
        return;
    }
    if (debug.messageEnabled()) {
        debug.message(method + "Meta Alias is : " + metaAlias);
        debug.message(method + "Remote EntityID is : " + remoteEntityID);
        debug.message(method + "Host EntityID is : " + hostEntityID);
    }
    try {
        String binding = SAML2Utils.getParameter(paramsMap, SAML2Constants.BINDING);
        ManageNameIDServiceElement mniService = getMNIServiceElement(realm, remoteEntityID, hostEntityRole, binding);
        if (binding == null) {
            binding = mniService.getBinding();
        }
        if (binding == null) {
            logError("UnableTofindBinding", LogUtil.METADATA_ERROR, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("UnableTofindBinding"));
        }
        String mniURL = null;
        if (mniService != null) {
            mniURL = mniService.getLocation();
        }
        if (mniURL == null) {
            logError("mniServiceNotFound", LogUtil.METADATA_ERROR, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("mniServiceNotFound"));
        }
        String requestType = (String) paramsMap.get("requestType");
        boolean changeID = "NewID".equals(requestType);
        String affiliationID = SAML2Utils.getParameter(paramsMap, SAML2Constants.AFFILIATION_ID);
        ManageNameIDRequest mniRequest = createManageNameIDRequest(session, realm, hostEntityID, hostEntityRole, remoteEntityID, mniURL, changeID, affiliationID);
        String relayState = SAML2Utils.getParameter(paramsMap, SAML2Constants.RELAY_STATE);
        if ((relayState == null) || (relayState.equals(""))) {
            relayState = SAML2Utils.getAttributeValueFromSSOConfig(realm, hostEntityID, hostEntityRole, SAML2Constants.DEFAULT_RELAY_STATE);
        }
        // Validate the RelayState URL.
        SAML2Utils.validateRelayStateURL(realm, hostEntityID, relayState, hostEntityRole);
        mniRequest.setDestination(XMLUtils.escapeSpecialCharacters(mniURL));
        saveMNIRequestInfo(request, response, paramsMap, mniRequest, relayState, hostEntityRole, session);
        String mniRequestXMLString = null;
        if (binding.equalsIgnoreCase(SAML2Constants.HTTP_REDIRECT)) {
            mniRequestXMLString = mniRequest.toXMLString(true, true);
            doMNIByHttpRedirect(mniRequestXMLString, mniURL, relayState, realm, hostEntityID, hostEntityRole, remoteEntityID, response);
        } else if (binding.equalsIgnoreCase(SAML2Constants.SOAP)) {
            signMNIRequest(mniRequest, realm, hostEntityID, hostEntityRole, remoteEntityID);
            BaseConfigType config = null;
            if (hostEntityRole.equalsIgnoreCase(SAML2Constants.SP_ROLE)) {
                config = metaManager.getIDPSSOConfig(realm, remoteEntityID);
            } else {
                config = metaManager.getSPSSOConfig(realm, remoteEntityID);
            }
            mniURL = SAML2Utils.fillInBasicAuthInfo(config, mniURL);
            if (!doMNIBySOAP(mniRequest, mniURL, metaAlias, hostEntityRole, request, response)) {
                throw new SAML2Exception(SAML2Utils.bundle.getString("mniFailed"));
            }
        } else if (binding.equalsIgnoreCase(SAML2Constants.HTTP_POST)) {
            signMNIRequest(mniRequest, realm, hostEntityID, hostEntityRole, remoteEntityID);
            mniRequestXMLString = mniRequest.toXMLString(true, true);
            doMNIByPOST(mniRequestXMLString, mniURL, relayState, realm, hostEntityID, hostEntityRole, remoteEntityID, response, request);
        }
    } catch (IOException ioe) {
        logError("errorCreatingMNIRequest", LogUtil.CANNOT_INSTANTIATE_MNI_REQUEST, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("errorCreatingMNIRequest"));
    } catch (SAML2MetaException sme) {
        logError("metaDataError", LogUtil.METADATA_ERROR, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    } catch (SessionException ssoe) {
        logError("invalidSSOToken", LogUtil.INVALID_SSOTOKEN, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("invalidSSOToken"));
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ManageNameIDServiceElement(com.sun.identity.saml2.jaxb.metadata.ManageNameIDServiceElement) BaseConfigType(com.sun.identity.saml2.jaxb.entityconfig.BaseConfigType) ManageNameIDRequest(com.sun.identity.saml2.protocol.ManageNameIDRequest) SessionException(com.sun.identity.plugin.session.SessionException) IOException(java.io.IOException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException)

Example 65 with SessionException

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

the class FSPostLogin method setTokenListenerAndSessionInfo.

/**
     * Sets the Session Listener and session information.
     *
     * @param request the <code>HttpServletRequest</code> object.
     * @param metaAlias the provider alias string.
     */
private void setTokenListenerAndSessionInfo(HttpServletRequest request, String metaAlias) {
    Object ssoToken = null;
    String sessionID = null;
    String userID = null;
    try {
        SessionProvider sessionProvider = SessionManager.getProvider();
        ssoToken = sessionProvider.getSession(request);
        sessionID = sessionProvider.getSessionID(ssoToken);
        userID = sessionProvider.getPrincipalName(ssoToken);
        sessionProvider.addListener(ssoToken, new FSTokenListener(metaAlias));
    } catch (SessionException ssoExp) {
        FSUtils.debug.error("FSPostLogin::setTokenListenerAndSessionInfo " + "Failed during trying to add token Listener:", ssoExp);
        return;
    }
    FSSessionManager sessionManager = FSSessionManager.getInstance(metaAlias);
    FSSession session = sessionManager.getSession(userID, sessionID);
    if (session == null) {
        if (FSUtils.debug.messageEnabled()) {
            FSUtils.debug.message("FSPostLogin::setTokenListenerAndSessionInfo. " + "No existing session found for user " + userID + " And SessionID: " + sessionID + " Creating a new Session");
        }
        FSSession newSession = new FSSession(sessionID);
        sessionManager.addSession(userID, newSession);
    }
}
Also used : FSSession(com.sun.identity.federation.services.FSSession) SessionException(com.sun.identity.plugin.session.SessionException) FSTokenListener(com.sun.identity.federation.services.logout.FSTokenListener) FSSessionManager(com.sun.identity.federation.services.FSSessionManager) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

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