Search in sources :

Example 1 with Issuer

use of com.sun.identity.saml2.assertion.Issuer in project OpenAM by OpenRock.

the class ECPRequestImpl method parseElement.

/* Parses the NameIDPolicy Element */
private void parseElement(Element element) throws SAML2Exception {
    if (element == null) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message("ECPRequestImpl.parseElement:" + " Input is null.");
        }
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    String localName = element.getLocalName();
    if (!REQUEST.equals(localName)) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message("ECPRequestImpl.parseElement:" + " element local name should be " + REQUEST);
        }
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidECPRequest"));
    }
    String namespaceURI = element.getNamespaceURI();
    if (!SAML2Constants.ECP_NAMESPACE.equals(namespaceURI)) {
        if (SAML2SDKUtils.debug.messageEnabled()) {
            SAML2SDKUtils.debug.message("ECPRequestImpl.parseElement:" + " element namespace should be " + SAML2Constants.ECP_NAMESPACE);
        }
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidECPNamesapce"));
    }
    String str = XMLUtils.getNodeAttributeValueNS(element, SAML2Constants.SOAP_ENV_NAMESPACE, SAML2Constants.MUST_UNDERSTAND);
    mustUnderstand = SAML2SDKUtils.StringToBoolean(str);
    actor = XMLUtils.getNodeAttributeValueNS(element, SAML2Constants.SOAP_ENV_NAMESPACE, SAML2Constants.ACTOR);
    providerName = XMLUtils.getNodeAttributeValue(element, SAML2Constants.PROVIDER_NAME);
    str = XMLUtils.getNodeAttributeValue(element, SAML2Constants.ISPASSIVE);
    isPassive = SAML2SDKUtils.StringToBoolean(str);
    NodeList nList = element.getChildNodes();
    if ((nList != null) && (nList.getLength() > 0)) {
        for (int i = 0; i < nList.getLength(); i++) {
            Node childNode = nList.item(i);
            if (childNode.getNodeType() != Node.ELEMENT_NODE) {
                continue;
            }
            String cName = childNode.getLocalName();
            if (cName.equals(SAML2Constants.ISSUER)) {
                validateIssuer();
                issuer = AssertionFactory.getInstance().createIssuer((Element) childNode);
            } else if (cName.equals(SAML2Constants.IDPLIST)) {
                validateIDPList();
                idpList = ProtocolFactory.getInstance().createIDPList((Element) childNode);
            } else {
                if (SAML2SDKUtils.debug.messageEnabled()) {
                    SAML2SDKUtils.debug.message("ECPRequestImpl.parseElement: " + "ECP Request has invalid child element");
                }
                throw new SAML2Exception(SAML2SDKUtils.bundle.getString("invalidElementECPReq"));
            }
        }
    }
    validateData();
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element)

Example 2 with Issuer

use of com.sun.identity.saml2.assertion.Issuer in project OpenAM by OpenRock.

the class UtilProxySAMLAuthenticator method authenticate.

@Override
public void authenticate() throws FederatedSSOException, IOException {
    final String classMethod = "UtilProxySAMLAuthenticator.authenticate: ";
    SPSSODescriptorElement spSSODescriptor = null;
    String preferredIDP;
    // There is no reqID, this is the first time that we pass here.
    String binding = SAML2Constants.HTTP_REDIRECT;
    if (request.getMethod().equals("POST")) {
        binding = SAML2Constants.HTTP_POST;
    }
    data.setAuthnRequest(getAuthnRequest(request, isFromECP, binding));
    if (data.getAuthnRequest() == null) {
        throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST);
    }
    data.getEventAuditor().setRequestId(data.getRequestID());
    data.setSpEntityID(data.getAuthnRequest().getIssuer().getValue());
    try {
        logAccess(isFromECP ? LogUtil.RECEIVED_AUTHN_REQUEST_ECP : LogUtil.RECEIVED_AUTHN_REQUEST, Level.INFO, data.getSpEntityID(), data.getIdpMetaAlias(), data.getAuthnRequest().toXMLString());
    } catch (SAML2Exception saml2ex) {
        SAML2Utils.debug.error(classMethod, saml2ex);
        throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST, saml2ex.getMessage());
    }
    if (!SAML2Utils.isSourceSiteValid(data.getAuthnRequest().getIssuer(), data.getRealm(), data.getIdpEntityID())) {
        SAML2Utils.debug.warning("{} Issuer in Request is not valid.", classMethod);
        throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST);
    }
    // verify the signature of the query string if applicable
    IDPSSODescriptorElement idpSSODescriptor;
    try {
        idpSSODescriptor = IDPSSOUtil.metaManager.getIDPSSODescriptor(data.getRealm(), data.getIdpEntityID());
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error(classMethod + "Unable to get IDP SSO Descriptor from meta.");
        throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
    }
    try {
        spSSODescriptor = IDPSSOUtil.metaManager.getSPSSODescriptor(data.getRealm(), data.getSpEntityID());
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error(classMethod + "Unable to get SP SSO Descriptor from meta.");
        SAML2Utils.debug.error(classMethod, sme);
    }
    if (isFromECP || idpSSODescriptor.isWantAuthnRequestsSigned() || (spSSODescriptor != null && spSSODescriptor.isAuthnRequestsSigned())) {
        // need to verify the query string containing authnRequest
        if (StringUtils.isBlank(data.getSpEntityID())) {
            throw new ClientFaultException(data.getIdpAdapter(), INVALID_SAML_REQUEST);
        }
        if (spSSODescriptor == null) {
            SAML2Utils.debug.error(classMethod + "Unable to get SP SSO Descriptor from meta.");
            throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
        }
        Set<X509Certificate> certificates = KeyUtil.getVerificationCerts(spSSODescriptor, data.getSpEntityID(), SAML2Constants.SP_ROLE);
        try {
            boolean isSignatureOK;
            if (isFromECP) {
                isSignatureOK = data.getAuthnRequest().isSignatureValid(certificates);
            } else {
                if ("POST".equals(request.getMethod())) {
                    isSignatureOK = data.getAuthnRequest().isSignatureValid(certificates);
                } else {
                    isSignatureOK = QuerySignatureUtil.verify(request.getQueryString(), certificates);
                }
            }
            if (!isSignatureOK) {
                SAML2Utils.debug.error(classMethod + "authn request verification failed.");
                throw new ClientFaultException(data.getIdpAdapter(), "invalidSignInRequest");
            }
            // In ECP profile, sp doesn't know idp.
            if (!isFromECP) {
                // verify Destination
                List ssoServiceList = idpSSODescriptor.getSingleSignOnService();
                String ssoURL = SPSSOFederate.getSSOURL(ssoServiceList, binding);
                if (!SAML2Utils.verifyDestination(data.getAuthnRequest().getDestination(), ssoURL)) {
                    SAML2Utils.debug.error(classMethod + "authn request destination verification failed.");
                    throw new ClientFaultException(data.getIdpAdapter(), "invalidDestination");
                }
            }
        } catch (SAML2Exception se) {
            SAML2Utils.debug.error(classMethod + "authn request verification failed.", se);
            throw new ClientFaultException(data.getIdpAdapter(), "invalidSignInRequest");
        }
        SAML2Utils.debug.message("{} authn request signature verification is successful.", classMethod);
    }
    SAML2Utils.debug.message("{} request id= {}", classMethod, data.getRequestID());
    if (data.getRequestID() == null) {
        SAML2Utils.debug.error(classMethod + "Request id is null");
        throw new ClientFaultException(data.getIdpAdapter(), "InvalidSAMLRequestID");
    }
    if (isFromECP) {
        try {
            IDPECPSessionMapper idpECPSessonMapper = IDPSSOUtil.getIDPECPSessionMapper(data.getRealm(), data.getIdpEntityID());
            data.setSession(idpECPSessonMapper.getSession(request, response));
        } catch (SAML2Exception se) {
            SAML2Utils.debug.message("Unable to retrieve user session.", classMethod);
        }
    } else {
        // get the user sso session from the request
        try {
            data.setSession(SessionManager.getProvider().getSession(request));
        } catch (SessionException se) {
            SAML2Utils.debug.message("{} Unable to retrieve user session.", classMethod);
        }
    }
    if (null != data.getSession()) {
        data.getEventAuditor().setAuthTokenId(data.getSession());
    }
    // will not trigger this adapter call
    if (preSingleSignOn(request, response, data)) {
        return;
    }
    // End of adapter invocation
    IDPAuthnContextMapper idpAuthnContextMapper = null;
    try {
        idpAuthnContextMapper = IDPSSOUtil.getIDPAuthnContextMapper(data.getRealm(), data.getIdpEntityID());
    } catch (SAML2Exception sme) {
        SAML2Utils.debug.error(classMethod, sme);
    }
    if (idpAuthnContextMapper == null) {
        SAML2Utils.debug.error(classMethod + "Unable to get IDPAuthnContextMapper from meta.");
        throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
    }
    IDPAuthnContextInfo idpAuthnContextInfo = null;
    try {
        idpAuthnContextInfo = idpAuthnContextMapper.getIDPAuthnContextInfo(data.getAuthnRequest(), data.getIdpEntityID(), data.getRealm());
    } catch (SAML2Exception sme) {
        SAML2Utils.debug.error(classMethod, sme);
    }
    if (idpAuthnContextInfo == null) {
        SAML2Utils.debug.message("{} Unable to find valid AuthnContext. Sending error Response.", classMethod);
        try {
            Response res = SAML2Utils.getErrorResponse(data.getAuthnRequest(), SAML2Constants.REQUESTER, SAML2Constants.NO_AUTHN_CONTEXT, null, data.getIdpEntityID());
            StringBuffer returnedBinding = new StringBuffer();
            String acsURL = IDPSSOUtil.getACSurl(data.getSpEntityID(), data.getRealm(), data.getAuthnRequest(), request, returnedBinding);
            String acsBinding = returnedBinding.toString();
            IDPSSOUtil.sendResponse(request, response, out, acsBinding, data.getSpEntityID(), data.getIdpEntityID(), data.getIdpMetaAlias(), data.getRealm(), data.getRelayState(), acsURL, res, data.getSession());
        } catch (SAML2Exception sme) {
            SAML2Utils.debug.error(classMethod, sme);
            throw new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
        }
        return;
    }
    // get the relay state query parameter from the request
    data.setRelayState(request.getParameter(SAML2Constants.RELAY_STATE));
    data.setMatchingAuthnContext(idpAuthnContextInfo.getAuthnContext());
    if (data.getSession() == null) {
        // the user has not logged in yet, redirect to auth
        redirectToAuth(spSSODescriptor, binding, idpAuthnContextInfo, data);
    } else {
        SAML2Utils.debug.message("{} There is an existing session", classMethod);
        // Let's verify that the realm is the same for the user and the IdP
        boolean isValidSessionInRealm = IDPSSOUtil.isValidSessionInRealm(data.getRealm(), data.getSession());
        String sessionIndex = IDPSSOUtil.getSessionIndex(data.getSession());
        boolean sessionUpgrade = false;
        if (isValidSessionInRealm) {
            sessionUpgrade = isSessionUpgrade(idpAuthnContextInfo, data.getSession());
            SAML2Utils.debug.message("{} IDP Session Upgrade is : {}", classMethod, sessionUpgrade);
        }
        // Holder for any exception encountered while redirecting for authentication:
        FederatedSSOException redirectException = null;
        if (sessionUpgrade || !isValidSessionInRealm || ((Boolean.TRUE.equals(data.getAuthnRequest().isForceAuthn())) && (!Boolean.TRUE.equals(data.getAuthnRequest().isPassive())))) {
            // sessionIndex
            if (sessionIndex != null && sessionIndex.length() != 0) {
                // Save the original IDP Session
                IDPSession oldIDPSession = IDPCache.idpSessionsByIndices.get(sessionIndex);
                if (oldIDPSession != null) {
                    IDPCache.oldIDPSessionCache.put(data.getRequestID(), oldIDPSession);
                } else {
                    SAML2Utils.debug.error(classMethod + "The old SAML2 session  was not found in the idp session " + "by indices cache");
                }
            }
            // Save the new requestId and AuthnRequest
            IDPCache.authnRequestCache.put(data.getRequestID(), new CacheObject(data.getAuthnRequest()));
            // Save the new requestId and AuthnContext
            IDPCache.idpAuthnContextCache.put(data.getRequestID(), new CacheObject(data.getMatchingAuthnContext()));
            // save if the request was an Session Upgrade case.
            IDPCache.isSessionUpgradeCache.add(data.getRequestID());
            // authenticates
            if (StringUtils.isNotBlank(data.getRelayState())) {
                IDPCache.relayStateCache.put(data.getRequestID(), data.getRelayState());
            }
            // Session upgrade could be requested by asking a greater AuthnContext
            if (isValidSessionInRealm) {
                try {
                    boolean isProxy = IDPProxyUtil.isIDPProxyEnabled(data.getAuthnRequest(), data.getRealm());
                    if (isProxy) {
                        preferredIDP = IDPProxyUtil.getPreferredIDP(data.getAuthnRequest(), data.getIdpEntityID(), data.getRealm(), request, response);
                        if (preferredIDP != null) {
                            if ((SPCache.reqParamHash != null) && (!(SPCache.reqParamHash.containsKey(preferredIDP)))) {
                                // IDP Proxy with configured proxy list
                                SAML2Utils.debug.message("{} IDP to be proxied {}", classMethod, preferredIDP);
                                IDPProxyUtil.sendProxyAuthnRequest(data.getAuthnRequest(), preferredIDP, spSSODescriptor, data.getIdpEntityID(), request, response, data.getRealm(), data.getRelayState(), binding);
                                return;
                            } else {
                                // IDP proxy with introduction cookie
                                Map paramsMap = (Map) SPCache.reqParamHash.get(preferredIDP);
                                paramsMap.put("authnReq", data.getAuthnRequest());
                                paramsMap.put("spSSODescriptor", spSSODescriptor);
                                paramsMap.put("idpEntityID", data.getIdpEntityID());
                                paramsMap.put("realm", data.getRealm());
                                paramsMap.put("relayState", data.getRelayState());
                                paramsMap.put("binding", binding);
                                SPCache.reqParamHash.put(preferredIDP, paramsMap);
                                return;
                            }
                        }
                    }
                //else continue for the local authentication.
                } catch (SAML2Exception re) {
                    SAML2Utils.debug.message("{} Redirecting for the proxy handling error: {}", classMethod, re.getMessage());
                    redirectException = new ServerFaultException(data.getIdpAdapter(), "UnableToRedirectToPreferredIDP", re.getMessage());
                }
            // End of IDP Proxy: Initiate proxying when session upgrade is requested
            }
            // Invoke the IDP Adapter before redirecting to authn
            if (preAuthenticationAdapter(request, response, data)) {
                return;
            }
            //we don't have a session
            try {
                //and they want to authenticate
                if (!Boolean.TRUE.equals(data.getAuthnRequest().isPassive())) {
                    redirectAuthentication(request, response, idpAuthnContextInfo, data, true);
                    return;
                } else {
                    try {
                        //and they want to get into the system with passive auth - response no passive
                        IDPSSOUtil.sendNoPassiveResponse(request, response, out, data.getIdpMetaAlias(), data.getIdpEntityID(), data.getRealm(), data.getAuthnRequest(), data.getRelayState(), data.getSpEntityID());
                    } catch (SAML2Exception sme) {
                        SAML2Utils.debug.error(classMethod, sme);
                        redirectException = new ServerFaultException(data.getIdpAdapter(), METADATA_ERROR);
                    }
                }
            } catch (IOException | SAML2Exception e) {
                SAML2Utils.debug.error(classMethod + "Unable to redirect to authentication.", e);
                sessionUpgrade = false;
                cleanUpCache(data.getRequestID());
                redirectException = new ServerFaultException(data.getIdpAdapter(), "UnableToRedirectToAuth", e.getMessage());
            }
        }
        // generate assertion response
        if (!sessionUpgrade && isValidSessionInRealm) {
            generateAssertionResponse(data);
        }
        if (redirectException != null) {
            throw redirectException;
        }
    }
}
Also used : IDPAuthnContextInfo(com.sun.identity.saml2.plugins.IDPAuthnContextInfo) IDPAuthnContextMapper(com.sun.identity.saml2.plugins.IDPAuthnContextMapper) IDPSession(com.sun.identity.saml2.profile.IDPSession) ServerFaultException(com.sun.identity.saml2.profile.ServerFaultException) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) SessionException(com.sun.identity.plugin.session.SessionException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) IDPECPSessionMapper(com.sun.identity.saml2.plugins.IDPECPSessionMapper) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Response(com.sun.identity.saml2.protocol.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) ClientFaultException(com.sun.identity.saml2.profile.ClientFaultException) List(java.util.List) CacheObject(com.sun.identity.saml2.profile.CacheObject) FederatedSSOException(com.sun.identity.saml2.profile.FederatedSSOException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) Map(java.util.Map) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 3 with Issuer

use of com.sun.identity.saml2.assertion.Issuer in project OpenAM by OpenRock.

the class SAML2TokenGenerationImpl method setIssuer.

private void setIssuer(Assertion assertion, SAML2Config config) throws TokenCreationException {
    final Issuer issuer = AssertionFactory.getInstance().createIssuer();
    try {
        issuer.setValue(config.getIdpId());
        assertion.setIssuer(issuer);
    } catch (SAML2Exception e) {
        throw new TokenCreationException(ResourceException.INTERNAL_ERROR, "Exception caught setting issuer in SAML2TokenGenerationImpl: " + e, e);
    }
}
Also used : SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Issuer(com.sun.identity.saml2.assertion.Issuer) TokenCreationException(org.forgerock.openam.sts.TokenCreationException)

Example 4 with Issuer

use of com.sun.identity.saml2.assertion.Issuer in project OpenAM by OpenRock.

the class SPACSUtils method getResponseFromArtifact.

// Retrieves response using artifact profile.
private static Response getResponseFromArtifact(String samlArt, String hostEntityId, HttpServletRequest request, HttpServletResponse response, String orgName, SAML2MetaManager sm) throws SAML2Exception, IOException {
    // decide which IDP and which artifact resolution service
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("SPACSUtils.getResponseFromArtifact: " + "samlArt = " + samlArt);
    }
    Artifact art = null;
    try {
        art = ProtocolFactory.getInstance().createArtifact(samlArt.trim());
        String[] data = { samlArt.trim() };
        LogUtil.access(Level.INFO, LogUtil.RECEIVED_ARTIFACT, data, null);
    } catch (SAML2Exception se) {
        SAML2Utils.debug.error("SPACSUtils.getResponseFromArtifact: " + "Unable to decode and parse artifact string:" + samlArt);
        SAMLUtils.sendError(request, response, response.SC_BAD_REQUEST, "errorObtainArtifact", SAML2Utils.bundle.getString("errorObtainArtifact"));
        throw se;
    }
    String idpEntityID = getIDPEntityID(art, request, response, orgName, sm);
    IDPSSODescriptorElement idp = null;
    try {
        idp = sm.getIDPSSODescriptor(orgName, idpEntityID);
    } catch (SAML2MetaException se) {
        String[] data = { orgName, idpEntityID };
        LogUtil.error(Level.INFO, LogUtil.IDP_META_NOT_FOUND, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "failedToGetIDPSSODescriptor", se.getMessage());
        throw se;
    }
    String location = getIDPArtifactResolutionServiceUrl(art.getEndpointIndex(), idpEntityID, idp, request, response);
    // create ArtifactResolve message
    ArtifactResolve resolve = null;
    SOAPMessage resMsg = null;
    try {
        resolve = ProtocolFactory.getInstance().createArtifactResolve();
        resolve.setID(SAML2Utils.generateID());
        resolve.setVersion(SAML2Constants.VERSION_2_0);
        resolve.setIssueInstant(new Date());
        resolve.setArtifact(art);
        resolve.setDestination(XMLUtils.escapeSpecialCharacters(location));
        Issuer issuer = AssertionFactory.getInstance().createIssuer();
        issuer.setValue(hostEntityId);
        resolve.setIssuer(issuer);
        String needArtiResolveSigned = SAML2Utils.getAttributeValueFromSSOConfig(orgName, idpEntityID, SAML2Constants.IDP_ROLE, SAML2Constants.WANT_ARTIFACT_RESOLVE_SIGNED);
        if (needArtiResolveSigned != null && needArtiResolveSigned.equals("true")) {
            // or save it somewhere?
            String signAlias = getAttributeValueFromSPSSOConfig(orgName, hostEntityId, sm, SAML2Constants.SIGNING_CERT_ALIAS);
            if (signAlias == null) {
                throw new SAML2Exception(SAML2Utils.bundle.getString("missingSigningCertAlias"));
            }
            KeyProvider kp = KeyUtil.getKeyProviderInstance();
            if (kp == null) {
                throw new SAML2Exception(SAML2Utils.bundle.getString("nullKeyProvider"));
            }
            resolve.sign(kp.getPrivateKey(signAlias), kp.getX509Certificate(signAlias));
        }
        String resolveString = resolve.toXMLString(true, true);
        if (SAML2Utils.debug.messageEnabled()) {
            SAML2Utils.debug.message("SPACSUtils.getResponseFromArtifact: " + "ArtifactResolve=" + resolveString);
        }
        SOAPConnection con = SOAPCommunicator.getInstance().openSOAPConnection();
        SOAPMessage msg = SOAPCommunicator.getInstance().createSOAPMessage(resolveString, true);
        IDPSSOConfigElement config = null;
        config = sm.getIDPSSOConfig(orgName, idpEntityID);
        location = SAML2Utils.fillInBasicAuthInfo(config, location);
        resMsg = con.call(msg, location);
    } catch (SAML2Exception s2e) {
        SAML2Utils.debug.error("SPACSUtils.getResponseFromArtifact: " + "couldn't create ArtifactResolve:", s2e);
        String[] data = { hostEntityId, art.getArtifactValue() };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_CREATE_ARTIFACT_RESOLVE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "errorCreateArtifactResolve", SAML2Utils.bundle.getString("errorCreateArtifactResolve"));
        throw s2e;
    } catch (SOAPException se) {
        SAML2Utils.debug.error("SPACSUtils.getResponseFromGet: " + "couldn't get ArtifactResponse. SOAP error:", se);
        String[] data = { hostEntityId, location };
        LogUtil.error(Level.INFO, LogUtil.CANNOT_GET_SOAP_RESPONSE, data, null);
        SAMLUtils.sendError(request, response, response.SC_INTERNAL_SERVER_ERROR, "errorInSOAPCommunication", SAML2Utils.bundle.getString("errorInSOAPCommunication"));
        throw new SAML2Exception(se.getMessage());
    }
    Response result = getResponseFromSOAP(resMsg, resolve, request, response, idpEntityID, idp, orgName, hostEntityId, sm);
    String[] data = { hostEntityId, idpEntityID, art.getArtifactValue(), "" };
    if (LogUtil.isAccessLoggable(Level.FINE)) {
        data[3] = result.toXMLString();
    }
    LogUtil.access(Level.INFO, LogUtil.GOT_RESPONSE_FROM_ARTIFACT, data, null);
    return result;
}
Also used : KeyProvider(com.sun.identity.saml.xmlsig.KeyProvider) Issuer(com.sun.identity.saml2.assertion.Issuer) SOAPConnection(javax.xml.soap.SOAPConnection) IDPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.IDPSSOConfigElement) SOAPMessage(javax.xml.soap.SOAPMessage) Artifact(com.sun.identity.saml2.protocol.Artifact) Date(java.util.Date) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) Response(com.sun.identity.saml2.protocol.Response) ArtifactResponse(com.sun.identity.saml2.protocol.ArtifactResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) ArtifactResolve(com.sun.identity.saml2.protocol.ArtifactResolve) SOAPException(javax.xml.soap.SOAPException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Example 5 with Issuer

use of com.sun.identity.saml2.assertion.Issuer in project OpenAM by OpenRock.

the class SPACSUtils method processResponseForFedlet.

/**
     * Processes response from Identity Provider to Fedlet (SP).
     * This will do all required protocol processing, include signature,
     * issuer and audience validation etc. A map containing processing
     * result will be returned. <br>
     * Here is a list of keys and values for the returned map: <br>
     * SAML2Constants.ATTRIBUTE_MAP -- Attribute map containing all attributes
     *                                 passed down from IDP inside the 
     *                                 Assertion. The value is a 
     *                                 <code>java.util.Map</code> whose keys 
     *                                 are attribute names and values are 
     *                                 <code>java.util.Set</code> of string 
     *                                 values for the attributes. <br>
     * SAML2Constants.RELAY_STATE -- Relay state, value is a string <br>
     * SAML2Constants.IDPENTITYID -- IDP entity ID, value is a string<br>
     * SAML2Constants.RESPONSE    -- Response object, value is an instance of 
     *                               com.sun.identity.saml2.protocol.Response
     * SAML2Constants.ASSERTION   -- Assertion object, value is an instance of 
     *                               com.sun.identity.saml2.assertion.Assertion
     * SAML2Constants.SUBJECT     -- Subject object, value is an instance of 
     *                               com.sun.identity.saml2.assertion.Subject
     * SAML2Constants.NAMEID      -- NameID object, value is an instance of 
     *                               com.sun.identity.saml2.assertion.NameID
     *
     * @param request HTTP Servlet request
     * @param response HTTP Servlet response.
     * @param out the print writer for writing out presentation
     *
     * @return <code>Map</code> which holds result of the processing.
     * @throws SAML2Exception if the processing failed due to server error.
     * @throws IOException if the processing failed due to IO error.
     * @throws SessionException if the processing failed due to session error.
     * @throws ServletException if the processing failed due to request error.
     *
     * @supported.api
     */
public static Map processResponseForFedlet(HttpServletRequest request, HttpServletResponse response, PrintWriter out) throws SAML2Exception, IOException, SessionException, ServletException {
    if ((request == null) || (response == null)) {
        throw new ServletException(SAML2SDKUtils.bundle.getString("nullInput"));
    }
    String requestURL = request.getRequestURL().toString();
    SAML2MetaManager metaManager = new SAML2MetaManager();
    if (metaManager == null) {
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("errorMetaManager"));
    }
    String metaAlias = SAML2MetaUtils.getMetaAliasByUri(requestURL);
    if ((metaAlias == null) || (metaAlias.length() == 0)) {
        // Check in case metaAlias has been supplied as a parameter
        metaAlias = request.getParameter(SAML2MetaManager.NAME_META_ALIAS_IN_URI);
        if (metaAlias == null || metaAlias.length() == 0) {
            // pick the first available one
            List spMetaAliases = metaManager.getAllHostedServiceProviderMetaAliases("/");
            if ((spMetaAliases != null) && !spMetaAliases.isEmpty()) {
                // get first one
                metaAlias = (String) spMetaAliases.get(0);
            }
            if ((metaAlias == null) || (metaAlias.length() == 0)) {
                throw new ServletException(SAML2SDKUtils.bundle.getString("nullSPEntityID"));
            }
        }
    }
    String hostEntityId = null;
    try {
        hostEntityId = metaManager.getEntityByMetaAlias(metaAlias);
    } catch (SAML2MetaException sme) {
        SAML2SDKUtils.debug.error("SPACSUtils.processResponseForFedlet", sme);
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
    }
    if (hostEntityId == null) {
        // logging?
        throw new SAML2Exception(SAML2SDKUtils.bundle.getString("metaDataError"));
    }
    // organization is always root org
    String orgName = "/";
    String relayState = request.getParameter(SAML2Constants.RELAY_STATE);
    SessionProvider sessionProvider = null;
    ResponseInfo respInfo = null;
    try {
        sessionProvider = SessionManager.getProvider();
    } catch (SessionException se) {
        SAML2SDKUtils.debug.error("SPACSUtils.processResponseForFedlet", se);
        throw new SAML2Exception(se);
    }
    respInfo = SPACSUtils.getResponse(request, response, orgName, hostEntityId, metaManager);
    Object newSession = null;
    // Throws a SAML2Exception if the response cannot be validated
    // or contains a non-Success StatusCode, invoking the SPAdapter SPI
    // for taking action on the failed validation.
    // The resulting exception has its redirectionDone flag set if
    // the SPAdapter issued a HTTP redirect.
    newSession = SPACSUtils.processResponse(request, response, out, metaAlias, null, respInfo, orgName, hostEntityId, metaManager, null);
    SAML2SDKUtils.debug.message("SSO SUCCESS");
    String[] redirected = sessionProvider.getProperty(newSession, SAML2Constants.RESPONSE_REDIRECTED);
    if ((redirected != null) && (redirected.length != 0) && redirected[0].equals("true")) {
        SAML2SDKUtils.debug.message("Already redirected in SPAdapter.");
        // response redirected already in SPAdapter
        return createMapForFedlet(respInfo, null, hostEntityId);
    }
    // redirect to relay state
    String finalUrl = SPACSUtils.getRelayState(relayState, orgName, hostEntityId, metaManager);
    String realFinalUrl = finalUrl;
    if (finalUrl != null && finalUrl.length() != 0) {
        try {
            realFinalUrl = sessionProvider.rewriteURL(newSession, finalUrl);
        } catch (SessionException se) {
            SAML2SDKUtils.debug.message("SPACSUtils.processRespForFedlet", se);
            realFinalUrl = finalUrl;
        }
    }
    String redirectUrl = SPACSUtils.getIntermediateURL(orgName, hostEntityId, metaManager);
    String realRedirectUrl = null;
    if (redirectUrl != null && redirectUrl.length() != 0) {
        if (realFinalUrl != null && realFinalUrl.length() != 0) {
            if (redirectUrl.indexOf("?") != -1) {
                redirectUrl += "&goto=";
            } else {
                redirectUrl += "?goto=";
            }
            redirectUrl += URLEncDec.encode(realFinalUrl);
            try {
                realRedirectUrl = sessionProvider.rewriteURL(newSession, redirectUrl);
            } catch (SessionException se) {
                SAML2SDKUtils.debug.message("SPACSUtils.processRespForFedlet: rewriting failed.", se);
                realRedirectUrl = redirectUrl;
            }
        } else {
            realRedirectUrl = redirectUrl;
        }
    } else {
        realRedirectUrl = finalUrl;
    }
    return createMapForFedlet(respInfo, realRedirectUrl, hostEntityId);
}
Also used : ServletException(javax.servlet.ServletException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) SessionException(com.sun.identity.plugin.session.SessionException) List(java.util.List) ArrayList(java.util.ArrayList) SAML2MetaManager(com.sun.identity.saml2.meta.SAML2MetaManager) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) SessionProvider(com.sun.identity.plugin.session.SessionProvider)

Aggregations

SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)48 Issuer (com.sun.identity.saml2.assertion.Issuer)42 Date (java.util.Date)24 List (java.util.List)20 ArrayList (java.util.ArrayList)19 SAML2MetaException (com.sun.identity.saml2.meta.SAML2MetaException)15 Element (org.w3c.dom.Element)15 Assertion (com.sun.identity.saml2.assertion.Assertion)13 Response (com.sun.identity.saml2.protocol.Response)13 SessionException (com.sun.identity.plugin.session.SessionException)12 X509Certificate (java.security.cert.X509Certificate)12 EncryptedAssertion (com.sun.identity.saml2.assertion.EncryptedAssertion)11 SPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement)11 HttpServletResponse (javax.servlet.http.HttpServletResponse)11 Node (org.w3c.dom.Node)10 NodeList (org.w3c.dom.NodeList)10 AssertionFactory (com.sun.identity.saml2.assertion.AssertionFactory)8 IDPSSODescriptorElement (com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)8 ProtocolFactory (com.sun.identity.saml2.protocol.ProtocolFactory)8 Status (com.sun.identity.saml2.protocol.Status)8