Search in sources :

Example 11 with Assertion

use of org.opensaml.saml.saml2.core.Assertion in project cas by apereo.

the class SamlProfileSamlConditionsBuilder method buildConditions.

private Conditions buildConditions(final AuthnRequest authnRequest, final Assertion assertion, final SamlRegisteredService service, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor) throws SamlException {
    final ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC);
    final Conditions conditions = newConditions(currentDateTime, currentDateTime.plusSeconds(casProperties.getAuthn().getSamlIdp().getResponse().getSkewAllowance()), adaptor.getEntityId());
    return conditions;
}
Also used : ZonedDateTime(java.time.ZonedDateTime) Conditions(org.opensaml.saml.saml2.core.Conditions)

Example 12 with Assertion

use of org.opensaml.saml.saml2.core.Assertion in project cloudstack by apache.

the class SAML2LoginAPIAuthenticatorCmd method authenticate.

@Override
public String authenticate(final String command, final Map<String, Object[]> params, final HttpSession session, final InetAddress remoteAddress, final String responseType, final StringBuilder auditTrailSb, final HttpServletRequest req, final HttpServletResponse resp) throws ServerApiException {
    try {
        if (!params.containsKey(SAMLPluginConstants.SAML_RESPONSE) && !params.containsKey("SAMLart")) {
            String idpId = null;
            String domainPath = null;
            if (params.containsKey(ApiConstants.IDP_ID)) {
                idpId = ((String[]) params.get(ApiConstants.IDP_ID))[0];
            }
            if (params.containsKey(ApiConstants.DOMAIN)) {
                domainPath = ((String[]) params.get(ApiConstants.DOMAIN))[0];
            }
            if (domainPath != null && !domainPath.isEmpty()) {
                if (!domainPath.startsWith("/")) {
                    domainPath = "/" + domainPath;
                }
                if (!domainPath.endsWith("/")) {
                    domainPath = domainPath + "/";
                }
            }
            SAMLProviderMetadata spMetadata = _samlAuthManager.getSPMetadata();
            SAMLProviderMetadata idpMetadata = _samlAuthManager.getIdPMetadata(idpId);
            if (idpMetadata == null) {
                throw new ServerApiException(ApiErrorCode.PARAM_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "IdP ID (" + idpId + ") is not found in our list of supported IdPs, cannot proceed.", params, responseType));
            }
            if (idpMetadata.getSsoUrl() == null || idpMetadata.getSsoUrl().isEmpty()) {
                throw new ServerApiException(ApiErrorCode.PARAM_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.PARAM_ERROR.getHttpCode(), "IdP ID (" + idpId + ") has no Single Sign On URL defined please contact " + idpMetadata.getContactPersonName() + " <" + idpMetadata.getContactPersonEmail() + ">, cannot proceed.", params, responseType));
            }
            String authnId = SAMLUtils.generateSecureRandomId();
            _samlAuthManager.saveToken(authnId, domainPath, idpMetadata.getEntityId());
            s_logger.debug("Sending SAMLRequest id=" + authnId);
            String redirectUrl = SAMLUtils.buildAuthnRequestUrl(authnId, spMetadata, idpMetadata, SAML2AuthManager.SAMLSignatureAlgorithm.value());
            resp.sendRedirect(redirectUrl);
            return "";
        }
        if (params.containsKey("SAMLart")) {
            throw new ServerApiException(ApiErrorCode.UNSUPPORTED_ACTION_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.UNSUPPORTED_ACTION_ERROR.getHttpCode(), "SAML2 HTTP Artifact Binding is not supported", params, responseType));
        } else {
            final String samlResponse = ((String[]) params.get(SAMLPluginConstants.SAML_RESPONSE))[0];
            Response processedSAMLResponse = this.processSAMLResponse(samlResponse);
            String statusCode = processedSAMLResponse.getStatus().getStatusCode().getValue();
            if (!statusCode.equals(StatusCode.SUCCESS_URI)) {
                throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Identity Provider send a non-successful authentication status code", params, responseType));
            }
            String username = null;
            Issuer issuer = processedSAMLResponse.getIssuer();
            SAMLProviderMetadata spMetadata = _samlAuthManager.getSPMetadata();
            SAMLProviderMetadata idpMetadata = _samlAuthManager.getIdPMetadata(issuer.getValue());
            String responseToId = processedSAMLResponse.getInResponseTo();
            s_logger.debug("Received SAMLResponse in response to id=" + responseToId);
            SAMLTokenVO token = _samlAuthManager.getToken(responseToId);
            if (token != null) {
                if (!(token.getEntity().equalsIgnoreCase(issuer.getValue()))) {
                    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "The SAML response contains Issuer Entity ID that is different from the original SAML request", params, responseType));
                }
            } else {
                throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Received SAML response for a SSO request that we may not have made or has expired, please try logging in again", params, responseType));
            }
            // Set IdpId for this session
            session.setAttribute(SAMLPluginConstants.SAML_IDPID, issuer.getValue());
            Signature sig = processedSAMLResponse.getSignature();
            if (idpMetadata.getSigningCertificate() != null && sig != null) {
                BasicX509Credential credential = new BasicX509Credential();
                credential.setEntityCertificate(idpMetadata.getSigningCertificate());
                SignatureValidator validator = new SignatureValidator(credential);
                try {
                    validator.validate(sig);
                } catch (ValidationException e) {
                    s_logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage());
                    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Response's signature failed to be validated by IDP signing key", params, responseType));
                }
            }
            if (username == null) {
                username = SAMLUtils.getValueFromAssertions(processedSAMLResponse.getAssertions(), SAML2AuthManager.SAMLUserAttributeName.value());
            }
            for (Assertion assertion : processedSAMLResponse.getAssertions()) {
                if (assertion != null && assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
                    session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
                    break;
                }
            }
            if (idpMetadata.getEncryptionCertificate() != null && spMetadata != null && spMetadata.getKeyPair() != null && spMetadata.getKeyPair().getPrivate() != null) {
                Credential credential = SecurityHelper.getSimpleCredential(idpMetadata.getEncryptionCertificate().getPublicKey(), spMetadata.getKeyPair().getPrivate());
                StaticKeyInfoCredentialResolver keyInfoResolver = new StaticKeyInfoCredentialResolver(credential);
                EncryptedKeyResolver keyResolver = new InlineEncryptedKeyResolver();
                Decrypter decrypter = new Decrypter(null, keyInfoResolver, keyResolver);
                decrypter.setRootInNewDocument(true);
                List<EncryptedAssertion> encryptedAssertions = processedSAMLResponse.getEncryptedAssertions();
                if (encryptedAssertions != null) {
                    for (EncryptedAssertion encryptedAssertion : encryptedAssertions) {
                        Assertion assertion = null;
                        try {
                            assertion = decrypter.decrypt(encryptedAssertion);
                        } catch (DecryptionException e) {
                            s_logger.warn("SAML EncryptedAssertion error: " + e.toString());
                        }
                        if (assertion == null) {
                            continue;
                        }
                        Signature encSig = assertion.getSignature();
                        if (idpMetadata.getSigningCertificate() != null && encSig != null) {
                            BasicX509Credential sigCredential = new BasicX509Credential();
                            sigCredential.setEntityCertificate(idpMetadata.getSigningCertificate());
                            SignatureValidator validator = new SignatureValidator(sigCredential);
                            try {
                                validator.validate(encSig);
                            } catch (ValidationException e) {
                                s_logger.error("SAML Response's signature failed to be validated by IDP signing key:" + e.getMessage());
                                throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "SAML Response's signature failed to be validated by IDP signing key", params, responseType));
                            }
                        }
                        if (assertion.getSubject() != null && assertion.getSubject().getNameID() != null) {
                            session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
                        }
                        if (username == null) {
                            username = SAMLUtils.getValueFromAttributeStatements(assertion.getAttributeStatements(), SAML2AuthManager.SAMLUserAttributeName.value());
                        }
                    }
                }
            }
            if (username == null) {
                throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Failed to find admin configured username attribute in the SAML Response. Please ask your administrator to check SAML user attribute name.", params, responseType));
            }
            UserAccount userAccount = null;
            List<UserAccountVO> possibleUserAccounts = _userAccountDao.getAllUsersByNameAndEntity(username, issuer.getValue());
            if (possibleUserAccounts != null && possibleUserAccounts.size() > 0) {
                // Users can switch to other allowed accounts later
                for (UserAccountVO possibleUserAccount : possibleUserAccounts) {
                    if (possibleUserAccount.getAccountState().equals(Account.State.enabled.toString())) {
                        userAccount = possibleUserAccount;
                        break;
                    }
                }
            }
            if (userAccount == null || userAccount.getExternalEntity() == null || !_samlAuthManager.isUserAuthorized(userAccount.getId(), issuer.getValue())) {
                throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Your authenticated user is not authorized for SAML Single Sign-On, please contact your administrator", params, responseType));
            }
            try {
                if (_apiServer.verifyUser(userAccount.getId())) {
                    LoginCmdResponse loginResponse = (LoginCmdResponse) _apiServer.loginUser(session, userAccount.getUsername(), userAccount.getUsername() + userAccount.getSource().toString(), userAccount.getDomainId(), null, remoteAddress, params);
                    SAMLUtils.setupSamlUserCookies(loginResponse, resp);
                    resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
                    return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
                }
            } catch (CloudAuthenticationException | IOException exception) {
                s_logger.debug("SAML Login failed to log in the user due to: " + exception.getMessage());
            }
        }
    } catch (IOException e) {
        auditTrailSb.append("SP initiated SAML authentication using HTTP redirection failed:");
        auditTrailSb.append(e.getMessage());
    }
    throw new ServerApiException(ApiErrorCode.ACCOUNT_ERROR, _apiServer.getSerializedApiError(ApiErrorCode.ACCOUNT_ERROR.getHttpCode(), "Unable to authenticate user while performing SAML based SSO. Please make sure your user/account has been added, enable and authorized by the admin before you can authenticate. Please contact your administrator.", params, responseType));
}
Also used : ValidationException(org.opensaml.xml.validation.ValidationException) Issuer(org.opensaml.saml2.core.Issuer) SAMLTokenVO(org.apache.cloudstack.saml.SAMLTokenVO) CloudAuthenticationException(com.cloud.exception.CloudAuthenticationException) StaticKeyInfoCredentialResolver(org.opensaml.xml.security.keyinfo.StaticKeyInfoCredentialResolver) ServerApiException(org.apache.cloudstack.api.ServerApiException) SAMLProviderMetadata(org.apache.cloudstack.saml.SAMLProviderMetadata) BasicX509Credential(org.opensaml.xml.security.x509.BasicX509Credential) Credential(org.opensaml.xml.security.credential.Credential) Assertion(org.opensaml.saml2.core.Assertion) EncryptedAssertion(org.opensaml.saml2.core.EncryptedAssertion) Decrypter(org.opensaml.saml2.encryption.Decrypter) IOException(java.io.IOException) LoginCmdResponse(org.apache.cloudstack.api.response.LoginCmdResponse) Response(org.opensaml.saml2.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) UserAccountVO(com.cloud.user.UserAccountVO) BasicX509Credential(org.opensaml.xml.security.x509.BasicX509Credential) EncryptedAssertion(org.opensaml.saml2.core.EncryptedAssertion) Signature(org.opensaml.xml.signature.Signature) SignatureValidator(org.opensaml.xml.signature.SignatureValidator) InlineEncryptedKeyResolver(org.opensaml.xml.encryption.InlineEncryptedKeyResolver) DecryptionException(org.opensaml.xml.encryption.DecryptionException) UserAccount(com.cloud.user.UserAccount) LoginCmdResponse(org.apache.cloudstack.api.response.LoginCmdResponse) InlineEncryptedKeyResolver(org.opensaml.xml.encryption.InlineEncryptedKeyResolver) EncryptedKeyResolver(org.opensaml.xml.encryption.EncryptedKeyResolver)

Example 13 with Assertion

use of org.opensaml.saml.saml2.core.Assertion in project ddf by codice.

the class LoginFilter method validateHolderOfKeyConfirmation.

private void validateHolderOfKeyConfirmation(SamlAssertionWrapper assertion, X509Certificate[] x509Certs) throws SecurityServiceException {
    List<String> confirmationMethods = assertion.getConfirmationMethods();
    boolean hasHokMethod = false;
    for (String method : confirmationMethods) {
        if (OpenSAMLUtil.isMethodHolderOfKey(method)) {
            hasHokMethod = true;
        }
    }
    if (hasHokMethod) {
        if (x509Certs != null && x509Certs.length > 0) {
            List<SubjectConfirmation> subjectConfirmations = assertion.getSaml2().getSubject().getSubjectConfirmations();
            for (SubjectConfirmation subjectConfirmation : subjectConfirmations) {
                if (OpenSAMLUtil.isMethodHolderOfKey(subjectConfirmation.getMethod())) {
                    Element dom = subjectConfirmation.getSubjectConfirmationData().getDOM();
                    Node keyInfo = dom.getFirstChild();
                    Node x509Data = keyInfo.getFirstChild();
                    Node dataNode = x509Data.getFirstChild();
                    Node dataText = dataNode.getFirstChild();
                    X509Certificate tlsCertificate = x509Certs[0];
                    if (dataNode.getLocalName().equals("X509Certificate")) {
                        String textContent = dataText.getTextContent();
                        byte[] byteValue = Base64.getMimeDecoder().decode(textContent);
                        try {
                            CertificateFactory cf = CertificateFactory.getInstance("X.509");
                            X509Certificate cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(byteValue));
                            //check that the certificate is still valid
                            cert.checkValidity();
                            //if the certs aren't the same, verify
                            if (!tlsCertificate.equals(cert)) {
                                //verify that the cert was signed by the same private key as the TLS cert
                                cert.verify(tlsCertificate.getPublicKey());
                            }
                        } catch (CertificateException | NoSuchAlgorithmException | InvalidKeyException | SignatureException | NoSuchProviderException e) {
                            throw new SecurityServiceException("Unable to validate Holder of Key assertion with certificate.");
                        }
                    } else if (dataNode.getLocalName().equals("X509SubjectName")) {
                        String textContent = dataText.getTextContent();
                        //If, however, the relying party does not trust the certificate issuer to issue such a DN, the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                        if (!tlsCertificate.getSubjectDN().getName().equals(textContent)) {
                            throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject DN.");
                        }
                    } else if (dataNode.getLocalName().equals("X509IssuerSerial")) {
                        //we have no way to support this confirmation type so we have to throw an error
                        throw new SecurityServiceException("Unable to validate Holder of Key assertion with issuer serial. NOT SUPPORTED");
                    } else if (dataNode.getLocalName().equals("X509SKI")) {
                        String textContent = dataText.getTextContent();
                        byte[] tlsSKI = tlsCertificate.getExtensionValue("2.5.29.14");
                        byte[] assertionSKI = Base64.getMimeDecoder().decode(textContent);
                        if (tlsSKI != null && tlsSKI.length > 0) {
                            ASN1OctetString tlsOs = ASN1OctetString.getInstance(tlsSKI);
                            ASN1OctetString assertionOs = ASN1OctetString.getInstance(assertionSKI);
                            SubjectKeyIdentifier tlsSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(tlsOs.getOctets());
                            SubjectKeyIdentifier assertSubjectKeyIdentifier = SubjectKeyIdentifier.getInstance(assertionOs.getOctets());
                            //the attesting entity is not confirmed and the relying party SHOULD disregard the assertion.
                            if (!Arrays.equals(tlsSubjectKeyIdentifier.getKeyIdentifier(), assertSubjectKeyIdentifier.getKeyIdentifier())) {
                                throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
                            }
                        } else {
                            throw new SecurityServiceException("Unable to validate Holder of Key assertion with subject key identifier.");
                        }
                    }
                }
            }
        } else {
            throw new SecurityServiceException("Holder of Key assertion, must be used with 2-way TLS.");
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) SecurityServiceException(ddf.security.service.SecurityServiceException) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) CertificateException(java.security.cert.CertificateException) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SignatureException(java.security.SignatureException) SubjectKeyIdentifier(org.bouncycastle.asn1.x509.SubjectKeyIdentifier) InvalidKeyException(java.security.InvalidKeyException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) SubjectConfirmation(org.opensaml.saml.saml2.core.SubjectConfirmation) ByteArrayInputStream(java.io.ByteArrayInputStream) NoSuchProviderException(java.security.NoSuchProviderException)

Example 14 with Assertion

use of org.opensaml.saml.saml2.core.Assertion in project ddf by codice.

the class IdpEndpoint method determineAuthMethod.

private AuthObj determineAuthMethod(String bodyStr, AuthnRequest authnRequest) {
    XMLStreamReader xmlStreamReader = null;
    try {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(new StringReader(bodyStr));
    } catch (XMLStreamException e) {
        LOGGER.debug("Unable to parse SOAP message from client.", e);
    }
    SoapMessage soapMessage = new SoapMessage(Soap11.getInstance());
    SAAJInInterceptor.SAAJPreInInterceptor preInInterceptor = new SAAJInInterceptor.SAAJPreInInterceptor();
    soapMessage.setContent(XMLStreamReader.class, xmlStreamReader);
    preInInterceptor.handleMessage(soapMessage);
    SAAJInInterceptor inInterceptor = new SAAJInInterceptor();
    inInterceptor.handleMessage(soapMessage);
    SOAPPart soapMessageContent = (SOAPPart) soapMessage.getContent(Node.class);
    AuthObj authObj = new AuthObj();
    try {
        Iterator soapHeaderElements = soapMessageContent.getEnvelope().getHeader().examineAllHeaderElements();
        while (soapHeaderElements.hasNext()) {
            SOAPHeaderElement soapHeaderElement = (SOAPHeaderElement) soapHeaderElements.next();
            if (soapHeaderElement.getLocalName().equals("Security")) {
                Iterator childElements = soapHeaderElement.getChildElements();
                while (childElements.hasNext()) {
                    Object nextElement = childElements.next();
                    if (nextElement instanceof SOAPElement) {
                        SOAPElement element = (SOAPElement) nextElement;
                        if (element.getLocalName().equals("UsernameToken")) {
                            Iterator usernameTokenElements = element.getChildElements();
                            Object next;
                            while (usernameTokenElements.hasNext()) {
                                if ((next = usernameTokenElements.next()) instanceof Element) {
                                    Element nextEl = (Element) next;
                                    if (nextEl.getLocalName().equals("Username")) {
                                        authObj.username = nextEl.getTextContent();
                                    } else if (nextEl.getLocalName().equals("Password")) {
                                        authObj.password = nextEl.getTextContent();
                                    }
                                }
                            }
                            if (authObj.username != null && authObj.password != null) {
                                authObj.method = USER_PASS;
                                break;
                            }
                        } else if (element.getLocalName().equals("Assertion") && element.getNamespaceURI().equals("urn:oasis:names:tc:SAML:2.0:assertion")) {
                            authObj.assertion = new SecurityToken(element.getAttribute("ID"), element, null, null);
                            authObj.method = SAML;
                            break;
                        }
                    }
                }
            }
        }
    } catch (SOAPException e) {
        LOGGER.debug("Unable to parse SOAP message.", e);
    }
    RequestedAuthnContext requestedAuthnContext = authnRequest.getRequestedAuthnContext();
    boolean requestingPki = false;
    boolean requestingUp = false;
    if (requestedAuthnContext != null) {
        List<AuthnContextClassRef> authnContextClassRefs = requestedAuthnContext.getAuthnContextClassRefs();
        for (AuthnContextClassRef authnContextClassRef : authnContextClassRefs) {
            String authnContextClassRefStr = authnContextClassRef.getAuthnContextClassRef();
            if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_X509.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SMARTCARD_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SOFTWARE_PKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_SPKI.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_TLS_CLIENT.equals(authnContextClassRefStr)) {
                requestingPki = true;
            } else if (SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD.equals(authnContextClassRefStr) || SAML2Constants.AUTH_CONTEXT_CLASS_REF_PASSWORD_PROTECTED_TRANSPORT.equals(authnContextClassRefStr)) {
                requestingUp = true;
            }
        }
    } else {
        //The requested auth context isn't required so we don't know what they want... just set both to true
        requestingPki = true;
        requestingUp = true;
    }
    if (requestingUp && authObj.method != null && authObj.method.equals(USER_PASS)) {
        LOGGER.trace("Found UsernameToken and correct AuthnContextClassRef");
        return authObj;
    } else if (requestingPki && authObj.method == null) {
        LOGGER.trace("Found no token, but client requested PKI AuthnContextClassRef");
        authObj.method = PKI;
        return authObj;
    } else if (authObj.method == null) {
        LOGGER.debug("No authentication tokens found for the current request and the client did not request PKI authentication");
    }
    return authObj;
}
Also used : SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) XMLStreamReader(javax.xml.stream.XMLStreamReader) Node(org.w3c.dom.Node) SOAPElement(javax.xml.soap.SOAPElement) SOAPHeaderElement(javax.xml.soap.SOAPHeaderElement) Element(org.w3c.dom.Element) AuthnContextClassRef(org.opensaml.saml.saml2.core.AuthnContextClassRef) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SAAJInInterceptor(org.apache.cxf.binding.soap.saaj.SAAJInInterceptor) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) RequestedAuthnContext(org.opensaml.saml.saml2.core.RequestedAuthnContext) XMLStreamException(javax.xml.stream.XMLStreamException) SOAPException(javax.xml.soap.SOAPException) StringReader(java.io.StringReader) SOAPPart(javax.xml.soap.SOAPPart) Iterator(java.util.Iterator) SOAPElement(javax.xml.soap.SOAPElement) SignableSAMLObject(org.opensaml.saml.common.SignableSAMLObject) SignableXMLObject(org.opensaml.xmlsec.signature.SignableXMLObject) XMLObject(org.opensaml.core.xml.XMLObject)

Example 15 with Assertion

use of org.opensaml.saml.saml2.core.Assertion in project ddf by codice.

the class IdpEndpoint method createCookie.

private NewCookie createCookie(HttpServletRequest request, org.opensaml.saml.saml2.core.Response response) {
    LOGGER.debug("Creating cookie for user.");
    if (response.getAssertions() != null && response.getAssertions().size() > 0) {
        Assertion assertion = response.getAssertions().get(0);
        if (assertion != null) {
            UUID uuid = UUID.randomUUID();
            cookieCache.cacheSamlAssertion(uuid.toString(), assertion.getDOM());
            URL url;
            try {
                url = new URL(request.getRequestURL().toString());
                LOGGER.debug("Returning new cookie for user.");
                return new NewCookie(COOKIE, uuid.toString(), SERVICES_IDP_PATH, url.getHost(), NewCookie.DEFAULT_VERSION, null, -1, null, true, true);
            } catch (MalformedURLException e) {
                LOGGER.info("Unable to create session cookie. Client will need to log in again.", e);
            }
        }
    }
    return null;
}
Also used : MalformedURLException(java.net.MalformedURLException) SecurityAssertion(ddf.security.assertion.SecurityAssertion) Assertion(org.opensaml.saml.saml2.core.Assertion) UUID(java.util.UUID) URL(java.net.URL) NewCookie(javax.ws.rs.core.NewCookie)

Aggregations

Assertion (org.opensaml.saml.saml2.core.Assertion)33 Response (org.opensaml.saml.saml2.core.Response)31 Element (org.w3c.dom.Element)31 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)26 Document (org.w3c.dom.Document)22 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)20 Status (org.opensaml.saml.saml2.core.Status)20 SAMLCallback (org.apache.wss4j.common.saml.SAMLCallback)18 DateTime (org.joda.time.DateTime)16 Test (org.junit.Test)16 Assertion (org.opensaml.saml.saml1.core.Assertion)13 InputStream (java.io.InputStream)11 Crypto (org.apache.wss4j.common.crypto.Crypto)11 AttributeStatement (org.opensaml.saml.saml2.core.AttributeStatement)11 ZonedDateTime (java.time.ZonedDateTime)10 XMLObject (org.opensaml.core.xml.XMLObject)10 KeyStore (java.security.KeyStore)9 Merlin (org.apache.wss4j.common.crypto.Merlin)9 Assertion (org.jasig.cas.client.validation.Assertion)9 AuthnRequest (org.opensaml.saml.saml2.core.AuthnRequest)9