Search in sources :

Example 11 with SOAPMessage

use of javax.xml.soap.SOAPMessage in project OpenAM by OpenRock.

the class LibertyManager method getMappedNameIdentifier.

/**
     * Returns <code>NameIdentifier</code> between the IDP and
     * the other SP for the same principal. This method should
     * be used by the code on the hosted SP, where the user
     * has logged in, and has an account linking with the IDP.
     * Futhermore, the same principal has an account linking
     * between his/her other (remote) SP account and the IDP
     * account.
     *
     * @param hostedSPMetaAlias The <code>metaAlias</code> of
     * the local service provider.
     * @param ssoToken The session token of the logged-
     * in user on the local service provider.
     * @param remoteSPEntityID The entity ID of the remote
     * service provider. In other words, it is the targeted
     * name space for the returned name identifier.
     * @return <code>NameIdentifier</code> of the same principal
     * but original established between the remote SP and
     * the IDP
     */
public static NameIdentifier getMappedNameIdentifier(String hostedSPMetaAlias, Object ssoToken, String remoteSPEntityID) {
    String classMethod = "LibertyManager.getMappedNameIdentifier: ";
    String hostedEntityID = getEntityID(hostedSPMetaAlias);
    String realm = IDFFMetaUtils.getRealmByMetaAlias(hostedSPMetaAlias);
    if (debug.messageEnabled()) {
        debug.message("NameMappingRequester: hostedEntityID=" + hostedEntityID);
    }
    SPDescriptorType hostedDescriptor = null;
    BaseConfigType hostedConfig = null;
    try {
        hostedDescriptor = metaManager.getSPDescriptor(realm, hostedEntityID);
        hostedConfig = metaManager.getSPDescriptorConfig(realm, hostedEntityID);
    } catch (IDFFMetaException ie) {
        debug.error(classMethod + "couldn't obtain hosted meta:", ie);
        return null;
    }
    String userID = null;
    try {
        userID = SessionManager.getProvider().getPrincipalName(ssoToken);
    } catch (SessionException ssoe) {
        debug.error("SessionException caught when trying to " + "get user DN from session token:", ssoe);
        return null;
    }
    if (debug.messageEnabled()) {
        debug.message(classMethod + "userID=" + userID);
    }
    FSNameMappingHandler handler = new FSNameMappingHandler(hostedEntityID, hostedDescriptor, hostedConfig, hostedSPMetaAlias);
    NameIdentifier ni = null;
    if (debug.messageEnabled()) {
        debug.message(classMethod + "targetNamespace (remoteSPEntityID)=" + remoteSPEntityID);
    }
    FSSessionManager sMgr = FSSessionManager.getInstance(hostedSPMetaAlias);
    FSSession sess = null;
    if (sMgr != null) {
        sess = sMgr.getSession(ssoToken);
    }
    FSSessionPartner partner = null;
    if (sess != null) {
        partner = sess.getCurrentSessionPartner();
    } else {
        debug.error(classMethod + "session is null");
        return null;
    }
    String remoteIDPEntityID = null;
    if (partner != null) {
        remoteIDPEntityID = partner.getPartner();
    }
    if (debug.messageEnabled()) {
        debug.message(classMethod + "Remote IDP EntityID = " + remoteIDPEntityID);
    }
    try {
        ni = handler.getNameIdentifier(userID, remoteIDPEntityID, true);
    } catch (Exception e) {
        debug.error(classMethod + "Exception caught when trying to get Name " + "Identifier between local SP and remote IDP: ", e);
        return null;
    }
    if (debug.messageEnabled()) {
        debug.message(classMethod + "Name Identifier between local SP and " + " remote IDP: " + ni.toString());
    }
    FSNameIdentifierMappingRequest mappingRequest = null;
    try {
        mappingRequest = new FSNameIdentifierMappingRequest(hostedEntityID, ni, remoteSPEntityID);
    } catch (com.sun.identity.federation.message.common.FSMsgException fe) {
        debug.error(classMethod, fe);
        return null;
    }
    if (FSServiceUtils.isSigningOn()) {
        try {
            mappingRequest.signXML(IDFFMetaUtils.getFirstAttributeValueFromConfig(hostedConfig, IFSConstants.SIGNING_CERT_ALIAS));
        } catch (SAMLException se) {
            debug.error(classMethod, se);
            return null;
        }
    }
    IDPDescriptorType remoteProviderDesc = null;
    try {
        remoteProviderDesc = metaManager.getIDPDescriptor(realm, remoteIDPEntityID);
    } catch (IDFFMetaException fme1) {
        debug.error(classMethod, fme1);
        return null;
    }
    String remoteSOAPEndPoint = remoteProviderDesc.getSoapEndpoint();
    if (debug.messageEnabled()) {
        debug.message(classMethod + "IDP's soap end point=" + remoteSOAPEndPoint);
    }
    FSSOAPService soapService = FSSOAPService.getInstance();
    SOAPMessage returnMsg = null;
    try {
        SOAPMessage msg = soapService.bind(mappingRequest.toXMLString(true, true));
        returnMsg = soapService.sendMessage(msg, remoteSOAPEndPoint);
    } catch (FSMsgException mex) {
        debug.error(classMethod, mex);
        return null;
    } catch (java.io.IOException ioe) {
        debug.error(classMethod, ioe);
        return null;
    } catch (javax.xml.soap.SOAPException soape) {
        debug.error(classMethod, soape);
        return null;
    }
    Element elt = soapService.parseSOAPMessage(returnMsg);
    FSNameIdentifierMappingResponse mappingResponse = null;
    try {
        mappingResponse = new FSNameIdentifierMappingResponse(elt);
    } catch (FSMsgException fme2) {
        debug.error(classMethod, fme2);
        return null;
    }
    if (debug.messageEnabled()) {
        String resStr = null;
        try {
            resStr = mappingResponse.toXMLString();
        } catch (FSMsgException fme3) {
            debug.error(classMethod, fme3);
            return null;
        }
        debug.message(classMethod + "NameIdentifierMappingResponse: " + resStr);
    }
    if (FSServiceUtils.isSigningOn()) {
        if (FSNameMappingHandler.verifyNameIdMappingResponseSignature(elt, returnMsg, realm)) {
            if (debug.messageEnabled()) {
                debug.message(classMethod + "Success in verifying Name Identifier Mapping" + " Response Signature");
            }
        } else {
            debug.error(classMethod + "Failed verifying Name Identifier Mapping " + "Response");
            return null;
        }
    }
    return mappingResponse.getNameIdentifier();
}
Also used : NameIdentifier(com.sun.identity.saml.assertion.NameIdentifier) FSSession(com.sun.identity.federation.services.FSSession) SessionException(com.sun.identity.plugin.session.SessionException) FSSOAPService(com.sun.identity.federation.services.FSSOAPService) SAMLException(com.sun.identity.saml.common.SAMLException) SOAPMessage(javax.xml.soap.SOAPMessage) BaseConfigType(com.sun.identity.federation.jaxb.entityconfig.BaseConfigType) FSSessionPartner(com.sun.identity.federation.services.FSSessionPartner) FSSessionManager(com.sun.identity.federation.services.FSSessionManager) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) FSNameIdentifierMappingResponse(com.sun.identity.federation.message.FSNameIdentifierMappingResponse) SPDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.SPDescriptorType) COTException(com.sun.identity.cot.COTException) SessionException(com.sun.identity.plugin.session.SessionException) SAMLException(com.sun.identity.saml.common.SAMLException) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) FSLoginHelperException(com.sun.identity.federation.services.FSLoginHelperException) FSAccountMgmtException(com.sun.identity.federation.accountmgmt.FSAccountMgmtException) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) IDPDescriptorType(com.sun.identity.liberty.ws.meta.jaxb.IDPDescriptorType) FSNameMappingHandler(com.sun.identity.federation.services.namemapping.FSNameMappingHandler) FSNameIdentifierMappingRequest(com.sun.identity.federation.message.FSNameIdentifierMappingRequest) FSMsgException(com.sun.identity.federation.message.common.FSMsgException)

Example 12 with SOAPMessage

use of javax.xml.soap.SOAPMessage in project OpenAM by OpenRock.

the class UtilProxySAMLAuthenticator method getAuthnRequest.

/**
     * Returns the <code>AuthnRequest</code> from HttpServletRequest
     */
private static AuthnRequest getAuthnRequest(HttpServletRequest request, boolean isFromECP, String binding) {
    if (isFromECP) {
        try {
            SOAPMessage msg = SOAPCommunicator.getInstance().getSOAPMessage(request);
            Element elem = SOAPCommunicator.getInstance().getSamlpElement(msg, SAML2Constants.AUTHNREQUEST);
            return ProtocolFactory.getInstance().createAuthnRequest(elem);
        } catch (Exception ex) {
            SAML2Utils.debug.error("IDPSSOFederate.getAuthnRequest:", ex);
        }
        return null;
    } else {
        String samlRequest = request.getParameter(SAML2Constants.SAML_REQUEST);
        if (samlRequest == null) {
            SAML2Utils.debug.error("IDPSSOFederate.getAuthnRequest: SAMLRequest is null");
            return null;
        }
        if (binding.equals(SAML2Constants.HTTP_REDIRECT)) {
            SAML2Utils.debug.message("IDPSSOFederate.getAuthnRequest: saml request = {}", samlRequest);
            return getAuthnRequest(samlRequest);
        } else if (binding.equals(SAML2Constants.HTTP_POST)) {
            ByteArrayInputStream bis = null;
            AuthnRequest authnRequest = null;
            try {
                byte[] raw = Base64.decode(samlRequest);
                if (raw != null) {
                    bis = new ByteArrayInputStream(raw);
                    Document doc = XMLUtils.toDOMDocument(bis, SAML2Utils.debug);
                    if (doc != null) {
                        SAML2Utils.debug.message("IDPSSOFederate.getAuthnRequest: decoded SAML2 Authn Request: {}", XMLUtils.print(doc.getDocumentElement()));
                        authnRequest = ProtocolFactory.getInstance().createAuthnRequest(doc.getDocumentElement());
                    } else {
                        SAML2Utils.debug.error("IDPSSOFederate.getAuthnRequest: Unable to parse SAMLRequest: " + samlRequest);
                    }
                }
            } catch (Exception ex) {
                SAML2Utils.debug.error("IDPSSOFederate.getAuthnRequest:", ex);
                return null;
            } finally {
                IOUtils.closeIfNotNull(bis);
            }
            return authnRequest;
        }
        return null;
    }
}
Also used : AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) ByteArrayInputStream(java.io.ByteArrayInputStream) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) Element(org.w3c.dom.Element) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement) Document(org.w3c.dom.Document) SOAPMessage(javax.xml.soap.SOAPMessage) ServletException(javax.servlet.ServletException) SessionException(com.sun.identity.plugin.session.SessionException) ClientFaultException(com.sun.identity.saml2.profile.ClientFaultException) ServerFaultException(com.sun.identity.saml2.profile.ServerFaultException) FederatedSSOException(com.sun.identity.saml2.profile.FederatedSSOException) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) IOException(java.io.IOException) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception)

Example 13 with SOAPMessage

use of javax.xml.soap.SOAPMessage in project OpenAM by OpenRock.

the class FSSingleLogoutHandler method doSoapProfile.

/**
     * Initiates SOAP proifle logout.
     * @param providerId the first provider with SOAP as logout profile
     */
private FSLogoutStatus doSoapProfile(String providerId) {
    FSUtils.debug.message("Entered IDP's doSoapProfile");
    try {
        FSSessionManager sMgr = FSSessionManager.getInstance(metaAlias);
        FSSession session = sMgr.getSession(ssoToken);
        FSAccountFedInfo currentAccount = null;
        if (session != null) {
            currentAccount = session.getAccountFedInfo();
        }
        if (currentAccount == null && !session.getOneTime()) {
            currentAccount = FSLogoutUtil.getCurrentWorkingAccount(userID, providerId, metaAlias);
        }
        if (currentAccount == null) {
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("FSSingleLogoutHandler. User's " + "account may have been terminated.");
            }
            return new FSLogoutStatus(IFSConstants.SAML_SUCCESS);
        }
        FSLogoutNotification reqLogout = createSingleLogoutRequest(currentAccount, sessionIndex);
        reqLogout.setMinorVersion(getMinorVersion(remoteDescriptor));
        if (reqLogout != null) {
            FSSOAPService instSOAP = FSSOAPService.getInstance();
            if (instSOAP != null) {
                FSUtils.debug.message("Signing suceeded. To call bindLogoutRequest");
                reqLogout.setID(IFSConstants.LOGOUTID);
                if (FSUtils.debug.messageEnabled()) {
                    FSUtils.debug.message("logout request before sign: " + reqLogout.toXMLString(true, true));
                }
                SOAPMessage msgLogout = instSOAP.bind(reqLogout.toXMLString(true, true));
                if (msgLogout != null) {
                    SOAPMessage retSOAPMessage = null;
                    try {
                        if (FSServiceUtils.isSigningOn()) {
                            int minorVersion = reqLogout.getMinorVersion();
                            switch(minorVersion) {
                                case IFSConstants.FF_11_PROTOCOL_MINOR_VERSION:
                                    msgLogout = signLogoutRequest(msgLogout, IFSConstants.ID, reqLogout.getID());
                                    break;
                                case IFSConstants.FF_12_PROTOCOL_MINOR_VERSION:
                                    msgLogout = signLogoutRequest(msgLogout, IFSConstants.REQUEST_ID, reqLogout.getRequestID());
                                    break;
                                default:
                                    FSUtils.debug.message("invalid minor version.");
                                    break;
                            }
                        }
                        retSOAPMessage = instSOAP.sendMessage(msgLogout, remoteDescriptor.getSoapEndpoint());
                    } catch (Exception e) {
                        FSUtils.debug.error("FSSOAPException in doSOAPProfile" + " Cannot send request", e);
                        return new FSLogoutStatus(IFSConstants.SAML_RESPONDER);
                    }
                    if (retSOAPMessage != null) {
                        Element elt = instSOAP.parseSOAPMessage(retSOAPMessage);
                        if (FSServiceUtils.isSigningOn()) {
                            if (!verifyResponseSignature(retSOAPMessage)) {
                                if (FSUtils.debug.messageEnabled()) {
                                    FSUtils.debug.message("Response " + "signature verification failed");
                                }
                                FSServiceUtils.returnLocallyAfterOperation(response, LOGOUT_DONE_URL, false, IFSConstants.LOGOUT_SUCCESS, IFSConstants.LOGOUT_FAILURE);
                                return new FSLogoutStatus(IFSConstants.SAML_REQUESTER);
                            }
                        }
                        this.requestLogout = reqLogout;
                        respObj = new FSLogoutResponse(elt);
                        // Call SP Adapter preSingleLogout for SP/SOAP
                        if (hostedRole != null && hostedRole.equalsIgnoreCase(IFSConstants.SP)) {
                            FederationSPAdapter spAdapter = FSServiceUtils.getSPAdapter(hostedEntityId, hostedConfig);
                            if (spAdapter != null) {
                                if (FSUtils.debug.messageEnabled()) {
                                    FSUtils.debug.message("FSSLOHandler." + "preSingleLogoutProcess, SP/SOAP");
                                }
                                try {
                                    spAdapter.preSingleLogoutProcess(hostedEntityId, request, response, userID, reqLogout, respObj, IFSConstants.LOGOUT_SP_SOAP_PROFILE);
                                } catch (Exception e) {
                                    // ignore adapter error
                                    FSUtils.debug.error("spAdapter." + "preSingleLogoutProcess, SP/SOAP:", e);
                                }
                            }
                        }
                        Status status = respObj.getStatus();
                        StatusCode statusCode = status.getStatusCode();
                        StatusCode secondLevelStatus = statusCode.getStatusCode();
                        String statusString = statusCode.getValue();
                        if (statusString.equalsIgnoreCase(IFSConstants.SAML_SUCCESS)) {
                            if (FSUtils.debug.messageEnabled()) {
                                FSUtils.debug.message("FSSingleLogoutHandler: " + " doSoapProfile returning success");
                            }
                            return new FSLogoutStatus(IFSConstants.SAML_SUCCESS);
                        } else {
                            if (FSUtils.debug.messageEnabled()) {
                                FSUtils.debug.message("FSSingleLogoutHandler: " + "SOAP Profile failure " + statusString);
                            }
                            return new FSLogoutStatus(statusString);
                        }
                    }
                }
            }
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("Unable to bindLogoutRequest." + "Current Provider cannot be processed");
            }
        } else {
            if (FSUtils.debug.messageEnabled()) {
                FSUtils.debug.message("Unable to create logout request" + " Current Provider cannot be processed");
            }
        }
    } catch (Exception e) {
        FSUtils.debug.error("In IOException of doSOAPProfile : ", e);
    }
    return new FSLogoutStatus(IFSConstants.SAML_RESPONDER);
}
Also used : Status(com.sun.identity.saml.protocol.Status) FSAccountFedInfo(com.sun.identity.federation.accountmgmt.FSAccountFedInfo) Element(org.w3c.dom.Element) FSSession(com.sun.identity.federation.services.FSSession) FSLogoutNotification(com.sun.identity.federation.message.FSLogoutNotification) FSSOAPService(com.sun.identity.federation.services.FSSOAPService) SOAPMessage(javax.xml.soap.SOAPMessage) FSLogoutResponse(com.sun.identity.federation.message.FSLogoutResponse) StatusCode(com.sun.identity.saml.protocol.StatusCode) ServletException(javax.servlet.ServletException) SAMLResponderException(com.sun.identity.saml.common.SAMLResponderException) SessionException(com.sun.identity.plugin.session.SessionException) SAMLException(com.sun.identity.saml.common.SAMLException) IDFFMetaException(com.sun.identity.federation.meta.IDFFMetaException) IOException(java.io.IOException) FSMsgException(com.sun.identity.federation.message.common.FSMsgException) FSSessionManager(com.sun.identity.federation.services.FSSessionManager) FederationSPAdapter(com.sun.identity.federation.plugins.FederationSPAdapter)

Example 14 with SOAPMessage

use of javax.xml.soap.SOAPMessage 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 15 with SOAPMessage

use of javax.xml.soap.SOAPMessage in project OpenAM by OpenRock.

the class SPSSOFederate method initiateECPRequest.

/**
     * Parses the request parameters and builds ECP Request to sent to the IDP.
     *
     * @param request the HttpServletRequest.
     * @param response the HttpServletResponse.
     *
     * @throws SAML2Exception if error creating AuthnRequest.
     * @throws IOException if error sending AuthnRequest to ECP.
     */
public static void initiateECPRequest(HttpServletRequest request, HttpServletResponse response) throws SAML2Exception, IOException {
    if (!isFromECP(request)) {
        SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest: " + "invalid HTTP request from ECP.");
        SAMLUtils.sendError(request, response, HttpServletResponse.SC_BAD_REQUEST, "invalidHttpRequestFromECP", SAML2Utils.bundle.getString("invalidHttpRequestFromECP"));
        return;
    }
    String metaAlias = request.getParameter("metaAlias");
    Map paramsMap = SAML2Utils.getParamsMap(request);
    // get the sp entity ID from the metaAlias
    String spEntityID = sm.getEntityByMetaAlias(metaAlias);
    String realm = getRealm(SAML2MetaUtils.getRealmByMetaAlias(metaAlias));
    if (SAML2Utils.debug.messageEnabled()) {
        SAML2Utils.debug.message("SPSSOFederate.initiateECPRequest: " + "spEntityID is " + spEntityID + ", realm is " + realm);
    }
    try {
        // Retreive MetaData 
        if (sm == null) {
            throw new SAML2Exception(SAML2Utils.bundle.getString("errorMetaManager"));
        }
        SPSSOConfigElement spEntityCfg = sm.getSPSSOConfig(realm, spEntityID);
        Map spConfigAttrsMap = null;
        if (spEntityCfg != null) {
            spConfigAttrsMap = SAML2MetaUtils.getAttributes(spEntityCfg);
        }
        // get SPSSODescriptor
        SPSSODescriptorElement spsso = sm.getSPSSODescriptor(realm, spEntityID);
        if (spsso == null) {
            String[] data = { spEntityID };
            LogUtil.error(Level.INFO, LogUtil.SP_METADATA_ERROR, data, null);
            throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        }
        String[] data = { spEntityID, realm };
        LogUtil.access(Level.INFO, LogUtil.RECEIVED_HTTP_REQUEST_ECP, data, null);
        List extensionsList = getExtensionsList(spEntityID, realm);
        // create AuthnRequest 
        AuthnRequest authnRequest = createAuthnRequest(realm, spEntityID, paramsMap, spConfigAttrsMap, extensionsList, spsso, null, null, true);
        // invoke SP Adapter class if registered
        SAML2ServiceProviderAdapter spAdapter = SAML2Utils.getSPAdapterClass(spEntityID, realm);
        if (spAdapter != null) {
            spAdapter.preSingleSignOnRequest(spEntityID, realm, null, request, response, authnRequest);
        }
        String alias = SAML2Utils.getSigningCertAlias(realm, spEntityID, SAML2Constants.SP_ROLE);
        PrivateKey signingKey = KeyUtil.getKeyProviderInstance().getPrivateKey(alias);
        if (signingKey != null) {
            authnRequest.sign(signingKey, null);
        } else {
            SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest: " + "Unable to find signing key.");
            throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
        }
        ECPFactory ecpFactory = ECPFactory.getInstance();
        // Default URL if relayState not present? in providerConfig?
        // TODO get Default URL from metadata 
        String relayState = getParameter(paramsMap, SAML2Constants.RELAY_STATE);
        String ecpRelayStateXmlStr = "";
        if (relayState != null && relayState.length() > 0) {
            String relayStateID = getRelayStateID(relayState, authnRequest.getID());
            ECPRelayState ecpRelayState = ecpFactory.createECPRelayState();
            ecpRelayState.setValue(relayStateID);
            ecpRelayState.setMustUnderstand(Boolean.TRUE);
            ecpRelayState.setActor(SAML2Constants.SOAP_ACTOR_NEXT);
            ecpRelayStateXmlStr = ecpRelayState.toXMLString(true, true);
        }
        ECPRequest ecpRequest = ecpFactory.createECPRequest();
        ecpRequest.setIssuer(createIssuer(spEntityID));
        ecpRequest.setMustUnderstand(Boolean.TRUE);
        ecpRequest.setActor(SAML2Constants.SOAP_ACTOR_NEXT);
        ecpRequest.setIsPassive(authnRequest.isPassive());
        SAML2IDPFinder ecpIDPFinder = SAML2Utils.getECPIDPFinder(realm, spEntityID);
        if (ecpIDPFinder != null) {
            List idps = ecpIDPFinder.getPreferredIDP(authnRequest, spEntityID, realm, request, response);
            if ((idps != null) && (!idps.isEmpty())) {
                SAML2MetaManager saml2MetaManager = SAML2Utils.getSAML2MetaManager();
                List idpEntries = null;
                for (Iterator iter = idps.iterator(); iter.hasNext(); ) {
                    String idpEntityID = (String) iter.next();
                    IDPSSODescriptorElement idpDesc = saml2MetaManager.getIDPSSODescriptor(realm, idpEntityID);
                    if (idpDesc != null) {
                        IDPEntry idpEntry = ProtocolFactory.getInstance().createIDPEntry();
                        idpEntry.setProviderID(idpEntityID);
                        String description = SAML2Utils.getAttributeValueFromSSOConfig(realm, idpEntityID, SAML2Constants.IDP_ROLE, SAML2Constants.ENTITY_DESCRIPTION);
                        idpEntry.setName(description);
                        List ssoServiceList = idpDesc.getSingleSignOnService();
                        String ssoURL = getSSOURL(ssoServiceList, SAML2Constants.SOAP);
                        idpEntry.setLoc(ssoURL);
                        if (idpEntries == null) {
                            idpEntries = new ArrayList();
                        }
                        idpEntries.add(idpEntry);
                    }
                }
                if (idpEntries != null) {
                    IDPList idpList = ProtocolFactory.getInstance().createIDPList();
                    idpList.setIDPEntries(idpEntries);
                    ecpRequest.setIDPList(idpList);
                    Map attrs = SAML2MetaUtils.getAttributes(spEntityCfg);
                    List values = (List) attrs.get(SAML2Constants.ECP_REQUEST_IDP_LIST_GET_COMPLETE);
                    if ((values != null) && (!values.isEmpty())) {
                        GetComplete getComplete = ProtocolFactory.getInstance().createGetComplete();
                        getComplete.setValue((String) values.get(0));
                        idpList.setGetComplete(getComplete);
                    }
                }
            }
        }
        String paosRequestXmlStr = "";
        try {
            PAOSRequest paosRequest = new PAOSRequest(authnRequest.getAssertionConsumerServiceURL(), SAML2Constants.PAOS_ECP_SERVICE, null, Boolean.TRUE, SAML2Constants.SOAP_ACTOR_NEXT);
            paosRequestXmlStr = paosRequest.toXMLString(true, true);
        } catch (PAOSException paosex) {
            SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest:", paosex);
            throw new SAML2Exception(paosex.getMessage());
        }
        String header = paosRequestXmlStr + ecpRequest.toXMLString(true, true) + ecpRelayStateXmlStr;
        String body = authnRequest.toXMLString(true, true);
        try {
            SOAPMessage reply = SOAPCommunicator.getInstance().createSOAPMessage(header, body, false);
            String[] data2 = { spEntityID, realm, "" };
            if (LogUtil.isAccessLoggable(Level.FINE)) {
                data2[2] = SOAPCommunicator.getInstance().soapMessageToString(reply);
            }
            LogUtil.access(Level.INFO, LogUtil.SEND_ECP_PAOS_REQUEST, data2, null);
            // are generated as part of the save.
            if (reply.saveRequired()) {
                reply.saveChanges();
            }
            response.setStatus(HttpServletResponse.SC_OK);
            SAML2Utils.putHeaders(reply.getMimeHeaders(), response);
            response.setContentType(PAOSConstants.PAOS_MIME_TYPE);
            // Write out the message on the response stream
            OutputStream os = response.getOutputStream();
            reply.writeTo(os);
            os.flush();
        } catch (SOAPException soapex) {
            SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest", soapex);
            String[] data3 = { spEntityID, realm };
            LogUtil.error(Level.INFO, LogUtil.SEND_ECP_PAOS_REQUEST_FAILED, data3, null);
            SAMLUtils.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "soapError", soapex.getMessage());
            return;
        }
        AuthnRequestInfo reqInfo = new AuthnRequestInfo(request, response, realm, spEntityID, null, authnRequest, relayState, paramsMap);
        synchronized (SPCache.requestHash) {
            SPCache.requestHash.put(authnRequest.getID(), reqInfo);
        }
        if (SAML2FailoverUtils.isSAML2FailoverEnabled()) {
            // sessionExpireTime is counted in seconds
            long sessionExpireTime = System.currentTimeMillis() / 1000 + SPCache.interval;
            String key = authnRequest.getID();
            try {
                SAML2FailoverUtils.saveSAML2TokenWithoutSecondaryKey(key, new AuthnRequestInfoCopy(reqInfo), sessionExpireTime);
                if (SAML2Utils.debug.messageEnabled()) {
                    SAML2Utils.debug.message("SPSSOFederate.initiateECPRequest:" + " SAVE AuthnRequestInfoCopy for requestID " + key);
                }
            } catch (SAML2TokenRepositoryException e) {
                SAML2Utils.debug.error("SPSSOFederate.initiateECPRequest: There was a problem saving the " + "AuthnRequestInfoCopy in the SAML2 Token Repository for requestID " + key, e);
            }
        }
    } catch (SAML2MetaException sme) {
        SAML2Utils.debug.error("SPSSOFederate:Error retrieving metadata", sme);
        throw new SAML2Exception(SAML2Utils.bundle.getString("metaDataError"));
    }
}
Also used : PrivateKey(java.security.PrivateKey) SPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.SPSSODescriptorElement) GetComplete(com.sun.identity.saml2.protocol.GetComplete) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) PAOSException(com.sun.identity.liberty.ws.paos.PAOSException) SOAPMessage(javax.xml.soap.SOAPMessage) ECPFactory(com.sun.identity.saml2.ecp.ECPFactory) SOAPException(javax.xml.soap.SOAPException) ECPRelayState(com.sun.identity.saml2.ecp.ECPRelayState) Iterator(java.util.Iterator) List(java.util.List) IDPList(com.sun.identity.saml2.protocol.IDPList) ArrayList(java.util.ArrayList) SAML2ServiceProviderAdapter(com.sun.identity.saml2.plugins.SAML2ServiceProviderAdapter) SAML2IDPFinder(com.sun.identity.saml2.plugins.SAML2IDPFinder) SAML2MetaException(com.sun.identity.saml2.meta.SAML2MetaException) ECPRequest(com.sun.identity.saml2.ecp.ECPRequest) SPSSOConfigElement(com.sun.identity.saml2.jaxb.entityconfig.SPSSOConfigElement) IDPList(com.sun.identity.saml2.protocol.IDPList) SAML2MetaManager(com.sun.identity.saml2.meta.SAML2MetaManager) SAML2Exception(com.sun.identity.saml2.common.SAML2Exception) AuthnRequest(com.sun.identity.saml2.protocol.AuthnRequest) SAML2TokenRepositoryException(org.forgerock.openam.federation.saml2.SAML2TokenRepositoryException) IDPEntry(com.sun.identity.saml2.protocol.IDPEntry) Map(java.util.Map) PAOSRequest(com.sun.identity.liberty.ws.paos.PAOSRequest) IDPSSODescriptorElement(com.sun.identity.saml2.jaxb.metadata.IDPSSODescriptorElement)

Aggregations

SOAPMessage (javax.xml.soap.SOAPMessage)219 SOAPException (javax.xml.soap.SOAPException)87 SOAPBody (javax.xml.soap.SOAPBody)47 Test (org.junit.Test)46 InputStream (java.io.InputStream)45 QName (javax.xml.namespace.QName)45 Element (org.w3c.dom.Element)44 IOException (java.io.IOException)40 MessageFactory (javax.xml.soap.MessageFactory)40 SoapMessage (org.apache.cxf.binding.soap.SoapMessage)30 SOAPElement (javax.xml.soap.SOAPElement)28 ByteArrayInputStream (java.io.ByteArrayInputStream)26 SAML2Exception (com.sun.identity.saml2.common.SAML2Exception)25 XMLStreamReader (javax.xml.stream.XMLStreamReader)25 Node (org.w3c.dom.Node)24 Document (org.w3c.dom.Document)22 URL (java.net.URL)21 SOAPPart (javax.xml.soap.SOAPPart)21 Exchange (org.apache.cxf.message.Exchange)19 MessageImpl (org.apache.cxf.message.MessageImpl)19