Search in sources :

Example 66 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 67 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)

Example 68 with Response

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

the class IDPProxyUtil method getNameIDFormat.

private static String getNameIDFormat(Response res) {
    if (res == null) {
        return null;
    }
    List assertions = res.getAssertion();
    if ((assertions == null) || (assertions.size() == 0)) {
        return null;
    }
    Assertion assertion = (Assertion) assertions.get(0);
    Subject subject = assertion.getSubject();
    if (subject == null) {
        return null;
    }
    NameID nameID = subject.getNameID();
    if (nameID == null) {
        return null;
    }
    String format = nameID.getFormat();
    return format;
}
Also used : NameID(com.sun.identity.saml2.assertion.NameID) Assertion(com.sun.identity.saml2.assertion.Assertion) List(java.util.List) IDPList(com.sun.identity.saml2.protocol.IDPList) ArrayList(java.util.ArrayList) Subject(com.sun.identity.saml2.assertion.Subject)

Example 69 with Response

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

the class DoManageNameID method signMNIResponse.

private static void signMNIResponse(ManageNameIDResponse mniResponse, String realm, String hostEntity, String hostEntityRole, String remoteEntity, boolean includeCert) throws SAML2Exception {
    String method = "signMNIResponse : ";
    boolean needResponseSign = false;
    if (hostEntityRole.equalsIgnoreCase(SAML2Constants.IDP_ROLE)) {
        needResponseSign = SAML2Utils.getWantMNIResponseSigned(realm, remoteEntity, SAML2Constants.SP_ROLE);
    } else {
        needResponseSign = SAML2Utils.getWantMNIResponseSigned(realm, remoteEntity, SAML2Constants.IDP_ROLE);
    }
    if (!needResponseSign) {
        if (debug.messageEnabled()) {
            debug.message(method + "MNIResponse doesn't need to be signed.");
        }
        return;
    }
    String alias = SAML2Utils.getSigningCertAlias(realm, hostEntity, hostEntityRole);
    if (debug.messageEnabled()) {
        debug.message(method + "realm is : " + realm);
        debug.message(method + "hostEntity is : " + hostEntity);
        debug.message(method + "Host Entity role is : " + hostEntityRole);
        debug.message(method + "Cert Alias is : " + alias);
        debug.message(method + "MNI Response before sign : " + mniResponse.toXMLString(true, true));
    }
    PrivateKey signingKey = keyProvider.getPrivateKey(alias);
    X509Certificate signingCert = null;
    if (includeCert) {
        signingCert = keyProvider.getX509Certificate(alias);
    }
    if (signingKey != null) {
        mniResponse.sign(signingKey, signingCert);
    } else {
        logError("missingSigningCertAlias", LogUtil.METADATA_ERROR, null);
        throw new SAML2Exception(SAML2Utils.bundle.getString("missingSigningCertAlias"));
    }
    if (debug.messageEnabled()) {
        debug.message(method + "MNI Response after sign : " + mniResponse.toXMLString(true, true));
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate)

Example 70 with Response

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

the class DoManageNameID method getMNIResponseFromPost.

static String getMNIResponseFromPost(String samlResponse, HttpServletResponse response) throws SAML2Exception {
    if (samlResponse == null) {
        throw new SAML2Exception(SAML2Utils.bundle.getString("missingSAMLResponse"));
    }
    ManageNameIDResponse resp = null;
    ByteArrayInputStream bis = null;
    try {
        byte[] raw = Base64.decode(samlResponse);
        if (raw != null) {
            bis = new ByteArrayInputStream(raw);
            Document doc = XMLUtils.toDOMDocument(bis, debug);
            if (doc != null) {
                resp = ProtocolFactory.getInstance().createManageNameIDResponse(doc.getDocumentElement());
            }
        }
    } catch (SAML2Exception se) {
        debug.error("DoManageNameID.getMNIResponseFromPost:", se);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullDecodedStrFromSamlResponse"));
    } catch (Exception e) {
        debug.error("DoManageNameID.getMNIResponseFromPost:", e);
        throw new SAML2Exception(SAML2Utils.bundle.getString("nullDecodedStrFromSamlResponse"));
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (Exception ie) {
                if (debug.messageEnabled()) {
                    debug.message("DoManageNameID.getMNIResponseFromPost:", ie);
                }
            }
        }
    }
    String respStr = null;
    if (resp != null) {
        respStr = resp.toXMLString();
    }
    if (debug.messageEnabled()) {
        debug.message("DoManageNameID.getMNIResponseFromPost: " + respStr);
    }
    return respStr;
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) ByteArrayInputStream(java.io.ByteArrayInputStream) Document(org.w3c.dom.Document) ManageNameIDResponse(com.sun.identity.saml2.protocol.ManageNameIDResponse) 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)

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