Search in sources :

Example 21 with Response

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

the class IDPSSOUtil method signAndEncryptResponseComponents.

/**
     * Signs and encrypts the components of a <code>SAML Response</code>
     * based on the service provider meta data. If the flag of
     * encrypting <code>Assertion</code> is on, then the embedded
     * <code>Assertion</code> object will be encrypted; if the flag
     * of encrypting <code>Assertion</code> is off and the flag of
     * encrypting <code>NameID</code> is on, then the <code>NameID</code>
     * embedded in the <code>Assertion</code> will be encrypted; if the
     * flag of encrypting <code>Assertion</code> is off and the flag of
     * encrypting <code>Attribute</code> is on, then the
     * <code>Attribute</code> embedded in the <code>Assertion</code>
     * will be encrypted. If the flag signAssertion is on, then the
     * <code>Assertion</code> will be signed. It will be signed before
     * it is encrypted and after its embedded <code>NameID</code> or
     * <code>Attribute</code> is encrypted.
     *
     * @param realm         the realm name of the identity provider
     * @param spEntityID    the entity id of the service provider
     * @param idpEntityID   the entity id of the identity provider
     * @param res           The <code>Response</code> whose components may be
     *                      encrypted based on the service provider meta data setting
     * @param signAssertion A flag to indicate if <code>Assertion</code>
     *                      signing is required
     */
static void signAndEncryptResponseComponents(String realm, String spEntityID, String idpEntityID, Response res, boolean signAssertion) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.signAndEncryptResponseComponents: ";
    boolean toEncryptAssertion = false;
    boolean toEncryptNameID = false;
    boolean toEncryptAttribute = false;
    if (res == null) {
        return;
    }
    List assertions = res.getAssertion();
    if ((assertions == null) || (assertions.size() == 0)) {
        return;
    }
    Assertion assertion = (Assertion) assertions.get(0);
    // get the encryption related flags from the SP Entity Config
    String wantAssertionEncrypted = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_ASSERTION_ENCRYPTED);
    toEncryptAssertion = (wantAssertionEncrypted != null) && (wantAssertionEncrypted.equals(SAML2Constants.TRUE));
    if (!toEncryptAssertion) {
        String wantNameIDEncrypted = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_NAMEID_ENCRYPTED);
        toEncryptNameID = (wantNameIDEncrypted != null) && (wantNameIDEncrypted.equals(SAML2Constants.TRUE));
        String wantAttributeEncrypted = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.WANT_ATTRIBUTE_ENCRYPTED);
        toEncryptAttribute = (wantAttributeEncrypted != null) && (wantAttributeEncrypted.equals(SAML2Constants.TRUE));
    }
    if ((!toEncryptAssertion) && (!toEncryptNameID) && (!toEncryptAttribute)) {
        // all encryption flags are off, no encryption needed
        if (signAssertion) {
            signAssertion(realm, idpEntityID, assertion);
            List assertionList = new ArrayList();
            assertionList.add(assertion);
            res.setAssertion(assertionList);
        }
        return;
    }
    SPSSODescriptorElement spSSODescriptorElement = getSPSSODescriptor(realm, spEntityID, classMethod);
    // get the encryption information
    EncInfo encInfo = KeyUtil.getEncInfo(spSSODescriptorElement, spEntityID, SAML2Constants.SP_ROLE);
    if (encInfo == null) {
        SAML2Utils.debug.error(classMethod + "failed to get service provider encryption key info.");
        throw new SAML2Exception(SAML2Utils.bundle.getString("UnableToFindEncryptKeyInfo"));
    }
    if (toEncryptAssertion) {
        // sign assertion first, then encrypt the assertion
        if (signAssertion) {
            signAssertion(realm, idpEntityID, assertion);
        }
        // we only encrypt the Assertion
        EncryptedAssertion encryptedAssertion = assertion.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), spEntityID);
        if (encryptedAssertion == null) {
            SAML2Utils.debug.error(classMethod + "failed to encrypt the assertion.");
            throw new SAML2Exception(SAML2Utils.bundle.getString("FailedToEncryptAssertion"));
        }
        List assertionList = new ArrayList();
        assertionList.add(encryptedAssertion);
        res.setEncryptedAssertion(assertionList);
        // reset assertion list
        res.setAssertion(new ArrayList());
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "Assertion encrypted.");
        }
    } else {
        // assertion if applicable
        if (toEncryptNameID) {
            // we need to encrypt the NameID            
            Subject subject = assertion.getSubject();
            if (subject == null) {
                return;
            }
            NameID nameID = subject.getNameID();
            if (nameID == null) {
                return;
            }
            EncryptedID encryptedNameID = nameID.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), spEntityID);
            if (encryptedNameID == null) {
                SAML2Utils.debug.error(classMethod + "failed to encrypt the NameID.");
                throw new SAML2Exception(SAML2Utils.bundle.getString("FailedToEncryptNameID"));
            }
            subject.setEncryptedID(encryptedNameID);
            // reset NameID
            subject.setNameID(null);
            assertion.setSubject(subject);
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "NameID encrypted.");
            }
        }
        if (toEncryptAttribute) {
            // we need to encrypt the Attribute
            List attributeStatements = assertion.getAttributeStatements();
            if ((attributeStatements != null) && (attributeStatements.size() > 0)) {
                int asSize = attributeStatements.size();
                // to hold all the AttributeStatements
                List stmts = new ArrayList();
                for (int i = 0; i < asSize; i++) {
                    AttributeStatement attributeStatement = (AttributeStatement) attributeStatements.get(i);
                    List attributes = attributeStatement.getAttribute();
                    if ((attributes == null) || (attributes.size() == 0)) {
                        continue;
                    }
                    int aSize = attributes.size();
                    // holds all the encrypted Attributes in this statement
                    List eaList = new ArrayList();
                    for (int j = 0; j < aSize; j++) {
                        Attribute attribute = (Attribute) attributes.get(j);
                        EncryptedAttribute encryptedAttribute = attribute.encrypt(encInfo.getWrappingKey(), encInfo.getDataEncAlgorithm(), encInfo.getDataEncStrength(), spEntityID);
                        if (encryptedAttribute == null) {
                            SAML2Utils.debug.error(classMethod + "failed to encrypt the Attribute.");
                            throw new SAML2Exception(SAML2Utils.bundle.getString("FailedToEncryptAttribute"));
                        }
                        eaList.add(encryptedAttribute);
                    }
                    attributeStatement.setEncryptedAttribute(eaList);
                    attributeStatement.setAttribute(new ArrayList());
                    stmts.add(attributeStatement);
                }
                assertion.setAttributeStatements(stmts);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "Attribute encrypted.");
                }
            }
        }
        if (signAssertion) {
            signAssertion(realm, idpEntityID, assertion);
        }
        List assertionList = new ArrayList();
        assertionList.add(assertion);
        res.setAssertion(assertionList);
    }
}
Also used : EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) NameID(com.sun.identity.saml2.assertion.NameID) Attribute(com.sun.identity.saml2.assertion.Attribute) EncryptedAttribute(com.sun.identity.saml2.assertion.EncryptedAttribute) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) Assertion(com.sun.identity.saml2.assertion.Assertion) ArrayList(java.util.ArrayList) EncryptedID(com.sun.identity.saml2.assertion.EncryptedID) Subject(com.sun.identity.saml2.assertion.Subject) EncInfo(com.sun.identity.saml2.key.EncInfo) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) EncryptedAssertion(com.sun.identity.saml2.assertion.EncryptedAssertion) AttributeStatement(com.sun.identity.saml2.assertion.AttributeStatement) List(java.util.List) ArrayList(java.util.ArrayList)

Example 22 with Response

use of com.sun.identity.saml2.protocol.Response 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 23 with Response

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

the class IDPSSOUtil method sendResponseArtifact.

/**
     * This method opens a URL connection to the target specified and
     * sends artifact response to it using the
     * <code>HttpServletResponse</code> object.
     *
     * @param response    the <code>HttpServletResponse</code> object
     * @param idpEntityID the entity id of the identity provider
     * @param realm       the realm name of the identity provider
     * @param acsURL      the assertion consumer service <code>URL</code>
     * @param relayState  the value of the <code>RelayState</code>
     * @param res         the <code>SAML Response</code> object
     * @param session     user session
     * @param props       property map including nameIDString for logging
     * @throws SAML2Exception if the operation is not successful
     */
public static void sendResponseArtifact(HttpServletRequest request, HttpServletResponse response, String idpEntityID, String spEntityID, String realm, String acsURL, String relayState, Response res, Object session, Map props) throws SAML2Exception {
    String classMethod = "IDPSSOUtil.sendResponseArtifact: ";
    IDPSSODescriptorElement idpSSODescriptorElement = null;
    try {
        idpSSODescriptorElement = metaManager.getIDPSSODescriptor(realm, idpEntityID);
        if (idpSSODescriptorElement == null) {
            SAML2Utils.debug.error(classMethod + "Unable to get IDP SSO Descriptor from meta.");
            String[] data = { idpEntityID };
            LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, session, props);
            throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        }
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error(classMethod + "Unable to get IDP SSO Descriptor from meta.");
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, session, props);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
    ArtifactResolutionServiceElement ars = (ArtifactResolutionServiceElement) idpSSODescriptorElement.getArtifactResolutionService().get(0);
    if (ars == null) {
        SAML2Utils.debug.error(classMethod + "Unable to get ArtifactResolutionServiceElement from meta.");
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, session, props);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
    Artifact art = null;
    try {
        art = ProtocolFactory.getInstance().createArtifact(null, ars.getIndex(), SAML2Utils.generateSourceID(idpEntityID), SAML2Utils.generateMessageHandleWithServerID());
    } catch (SAML2Exception se) {
        SAML2Utils.debug.error(classMethod + "Unable to create artifact: ", se);
        String[] data = { idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_CREATE_ARTIFACT, data, session, props);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "errorCreateArtifact", SAML2Utils.bundle.getString("errorCreateArtifact"));
        return;
    }
    String artStr = art.getArtifactValue();
    try {
        IDPCache.responsesByArtifacts.put(artStr, res);
        if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            try {
                long expireTime = getValidTimeofResponse(realm, idpEntityID, res) / 1000;
                SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(artStr, res.toXMLString(true, true), expireTime);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message(classMethod + "Saved Response to SAML2 Token Repository using key " + artStr);
                }
            } catch (SAML2TokenRepositoryException se) {
                SAML2Utils.debug.error(classMethod + "Unable to save Response to the SAML2 Token Repository", se);
            }
        }
        String messageEncoding = SAML2Utils.getAttributeValueFromSSOConfig(realm, spEntityID, SAML2Constants.SP_ROLE, SAML2Constants.RESPONSE_ARTIFACT_MESSAGE_ENCODING);
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + "messageEncoding = " + messageEncoding);
            SAML2Utils.debug.message(classMethod + "artStr = " + artStr);
        }
        if ((messageEncoding != null) && (messageEncoding.equals(SAML2Constants.FORM_ENCODING))) {
            String[] logdata = { idpEntityID, realm, acsURL };
            LogUtil.access(Level.INFO, LogUtil.SEND_ARTIFACT, logdata, session, props);
            SAML2Utils.postToTarget(request, response, SAML2Constants.SAML_ART, artStr, "RelayState", relayState, acsURL);
        } else {
            String redirectURL = acsURL + (acsURL.contains("?") ? "&" : "?") + "SAMLart=" + URLEncDec.encode(artStr);
            if ((relayState != null) && (relayState.trim().length() != 0)) {
                redirectURL += "&RelayState=" + URLEncDec.encode(relayState);
            }
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + "Redirect URL = " + redirectURL);
            }
            String[] logdata = { idpEntityID, realm, redirectURL };
            LogUtil.access(Level.INFO, LogUtil.SEND_ARTIFACT, logdata, session, props);
            response.sendRedirect(redirectURL);
        }
    } catch (IOException ioe) {
        SAML2Utils.debug.error(classMethod + "Unable to send redirect: ", ioe);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) IOException(java.io.IOException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) ArtifactResolutionServiceElement(com.sun.identity.saml2.jaxb.metadata.ArtifactResolutionServiceElement) Artifact(com.sun.identity.saml2.protocol.Artifact) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 24 with Response

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

the class IDPProxyUtil method sendProxyAuthnRequest.

/**
     * Sends a new AuthnRequest to the authenticating provider. 
     * @param authnRequest original AuthnRequest sent by the service provider.
     * @param preferredIDP IDP to be proxied. 
     * @param spSSODescriptor SPSSO Descriptor Element
     * @param hostedEntityId hosted provider ID 
     * @param request HttpServletRequest 
     * @param response HttpServletResponse
     * @param realm Realm
     * @param relayState the Relay State 
     * @param originalBinding The binding used to send the original AuthnRequest.
     * @exception SAML2Exception for any SAML2 failure.
     * @exception IOException if there is a failure in redirection.
     */
public static void sendProxyAuthnRequest(AuthnRequest authnRequest, String preferredIDP, SPSSODescriptorElement spSSODescriptor, String hostedEntityId, HttpServletRequest request, HttpServletResponse response, String realm, String relayState, String originalBinding) throws SAML2Exception, IOException {
    String classMethod = "IDPProxyUtil.sendProxyAuthnRequest: ";
    String destination = null;
    SPSSODescriptorElement localDescriptor = null;
    SPSSOConfigElement localDescriptorConfig = null;
    IDPSSODescriptorElement idpDescriptor = null;
    String binding;
    try {
        idpDescriptor = IDPSSOUtil.metaManager.getIDPSSODescriptor(realm, preferredIDP);
        List<SingleSignOnServiceElement> ssoServiceList = idpDescriptor.getSingleSignOnService();
        SingleSignOnServiceElement endpoint = getMatchingSSOEndpoint(ssoServiceList, originalBinding);
        if (endpoint == null) {
            SAML2Utils.debug.error(classMethod + "Single Sign-on service is not found for the proxying IDP.");
            throw new SAML2Exception(SAML2Utils.bundle.getString("ssoServiceNotFoundIDPProxy"));
        }
        binding = endpoint.getBinding();
        destination = endpoint.getLocation();
        localDescriptor = IDPSSOUtil.metaManager.getSPSSODescriptor(realm, hostedEntityId);
        localDescriptorConfig = IDPSSOUtil.metaManager.getSPSSOConfig(realm, hostedEntityId);
    } catch (SAML2MetaException e) {
        SAML2Utils.debug.error(classMethod, e);
        throw new SAML2Exception(e.getMessage());
    }
    AuthnRequest newAuthnRequest = getNewAuthnRequest(hostedEntityId, destination, realm, authnRequest);
    // invoke SP Adapter class if registered
    SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(hostedEntityId, realm);
    if (spAdapter != null) {
        spAdapter.preSingleSignOnRequest(hostedEntityId, preferredIDP, realm, request, response, newAuthnRequest);
    }
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message(classMethod + "New Authentication request:" + newAuthnRequest.toXMLString());
    }
    String requestID = newAuthnRequest.getID();
    // save the AuthnRequest in the IDPCache so that it can be
    // retrieved later when the user successfully authenticates
    IDPCache.authnRequestCache.put(requestID, newAuthnRequest);
    // save the original AuthnRequest
    IDPCache.proxySPAuthnReqCache.put(requestID, authnRequest);
    boolean signingNeeded = idpDescriptor.isWantAuthnRequestsSigned() || localDescriptor.isAuthnRequestsSigned();
    // check if relayState is present and get the unique
    // id which will be appended to the SSO URL before
    // redirecting
    String relayStateID = null;
    if (relayState != null && relayState.length() > 0) {
        relayStateID = SPSSOFederate.getRelayStateID(relayState, authnRequest.getID());
    }
    if (binding.equals(SAML2Constants.HTTP_POST)) {
        if (signingNeeded) {
            String certAlias = SPSSOFederate.getParameter(SAML2MetaUtils.getAttributes(localDescriptorConfig), SAML2Constants.SIGNING_CERT_ALIAS);
            SPSSOFederate.signAuthnRequest(certAlias, newAuthnRequest);
        }
        String authXMLString = newAuthnRequest.toXMLString(true, true);
        String encodedReqMsg = SAML2Utils.encodeForPOST(authXMLString);
        SAML2Utils.postToTarget(request, response, "SAMLRequest", encodedReqMsg, "RelayState", relayStateID, destination);
    } else {
        String authReqXMLString = newAuthnRequest.toXMLString(true, true);
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message(classMethod + " AuthnRequest: " + authReqXMLString);
        }
        String encodedXML = SAML2Utils.encodeForRedirect(authReqXMLString);
        StringBuffer queryString = new StringBuffer().append(SAML2Constants.SAML_REQUEST).append(SAML2Constants.EQUAL).append(encodedXML);
        //TODO:  should it be newAuthnRequest??? 
        if (relayStateID != null && relayStateID.length() > 0) {
            queryString.append("&").append(SAML2Constants.RELAY_STATE).append("=").append(URLEncDec.encode(relayStateID));
        }
        StringBuffer redirectURL = new StringBuffer().append(destination).append(destination.contains("?") ? "&" : "?");
        if (signingNeeded) {
            String certAlias = SPSSOFederate.getParameter(SAML2MetaUtils.getAttributes(localDescriptorConfig), SAML2Constants.SIGNING_CERT_ALIAS);
            String signedQueryStr = SPSSOFederate.signQueryString(queryString.toString(), certAlias);
            redirectURL.append(signedQueryStr);
        } else {
            redirectURL.append(queryString);
        }
        response.sendRedirect(redirectURL.toString());
    }
    String[] data = { destination };
    LogUtil.access(Level.INFO, LogUtil.REDIRECT_TO_SP, data, null);
    AuthnRequestInfo reqInfo = new AuthnRequestInfo(request, response, realm, hostedEntityId, preferredIDP, newAuthnRequest, relayState, null);
    synchronized (SPCache.requestHash) {
        SPCache.requestHash.put(requestID, reqInfo);
    }
    if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
        try {
            // sessionExpireTime is counted in seconds
            long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
            SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(requestID, new AuthnRequestInfoCopy(reqInfo), sessionExpireTime);
            if (SAML2Utils.debug.messageEnabled()) {
                SAML2Utils.debug.message(classMethod + " SAVE AuthnRequestInfoCopy for requestID " + requestID);
            }
        } catch (SAML2TokenRepositoryException se) {
            SAML2Utils.debug.error(classMethod + " SAVE AuthnRequestInfoCopy for requestID " + requestID + ", failed!", se);
        }
    }
}
Also used : SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) SingleSignOnServiceElement(com.sun.identity.saml2.jaxb.metadata.SingleSignOnServiceElement) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) SAML2ServiceProviderAdapter(com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 25 with Response

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

the class IDPProxyUtil method getLocation.

/**
     * Gets the SLO response service location of the authenticating 
     * identity provider
     * @param realm Realm
     * @param idpEntityID authenticating identity provider. 
     * @return location URL of the SLO response service, return null 
     * if not found.
     */
public static String getLocation(String realm, String idpEntityID, String binding) {
    try {
        String location = null;
        // get IDPSSODescriptor
        IDPSSODescriptorElement idpsso = sm.getIDPSSODescriptor(realm, idpEntityID);
        if (idpsso == null) {
            String[] data = { idpEntityID };
            LogUtil.error(Level.INFO, LogUtil.IDP_METADATA_ERROR, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        }
        List slosList = idpsso.getSingleLogoutService();
        if (slosList == null) {
            String[] data = { idpEntityID };
            LogUtil.error(Level.INFO, LogUtil.SLO_NOT_FOUND, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("sloServiceListNotfound"));
        }
        location = LogoutUtil.getSLOServiceLocation(slosList, binding);
        if (SAML2Utils.debug.messageEnabled() && (location != null) && (!location.equals(""))) {
            SAML2Utils.debug.message("Location URL: " + location);
        }
        return location;
    } catch (SAML2Exception se) {
        return null;
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) List(java.util.List) IDPList(com.sun.identity.saml2.protocol.IDPList) ArrayList(java.util.ArrayList) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)119 List (java.util.List)53 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)45 ArrayList (java.util.ArrayList)41 IOException (java.io.IOException)40 SessionException (com.sun.identity.plugin.session.SessionException)35 Response (com.sun.identity.saml2.protocol.Response)31 SOAPException (javax.xml.soap.SOAPException)31 Issuer (com.sun.identity.saml2.assertion.Issuer)28 HttpServletResponse (javax.servlet.http.HttpServletResponse)28 SAML2TokenRepositoryException (org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException)25 Map (java.util.Map)24 Assertion (com.sun.identity.saml2.assertion.Assertion)23 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)23 SOAPMessage (javax.xml.soap.SOAPMessage)22 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)20 Date (java.util.Date)20 HashMap (java.util.HashMap)20 Element (org.w3c.dom.Element)20 X509Certificate (java.security.cert.X509Certificate)16