Search in sources :

Example 71 with Assertion

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

the class AttributeQueryClient method retrieveResponse.

/**
     * Retrieves the response and returns its SAML Assertion.
     *
     * @param requestDocument of the request.
     * @return Assertion of the response or null if the response is empty.
     * @throws AttributeQueryException
     */
private Assertion retrieveResponse(Document requestDocument) throws AttributeQueryException {
    Assertion assertion = null;
    try {
        Document responseDocument = sendRequest(requestDocument);
        if (responseDocument == null) {
            return null;
        }
        // Print Response
        if (LOGGER.isTraceEnabled()) {
            printXML("SAML Response:\n {}", responseDocument);
        }
        // Extract Response from Soap message.
        NodeList elementsByTagNameNS = responseDocument.getElementsByTagNameNS(SAML2_PROTOCOL, "Response");
        if (elementsByTagNameNS == null) {
            throw new AttributeQueryException("Unable to find SAML Response.");
        }
        Node responseNode = elementsByTagNameNS.item(0);
        Element responseElement = (Element) responseNode;
        Unmarshaller unmarshaller = XMLObjectProviderRegistrySupport.getUnmarshallerFactory().getUnmarshaller(responseElement);
        Response response = (Response) unmarshaller.unmarshall(responseElement);
        LOGGER.debug("Successfully marshalled Element to SAML Response.");
        if (response.getStatus().getStatusCode().getValue().equals(SAML2_SUCCESS)) {
            LOGGER.debug("Successful response, retrieved attributes.");
            // Should only have one assertion.
            assertion = response.getAssertions().get(0);
        } else {
            reportError(response.getStatus());
        }
        return assertion;
    } catch (UnmarshallingException e) {
        throw new AttributeQueryException("Unable to marshall Element to SAML Response.", e);
    }
}
Also used : Response(org.opensaml.saml.saml2.core.Response) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Assertion(org.opensaml.saml.saml2.core.Assertion) Document(org.w3c.dom.Document) Unmarshaller(org.opensaml.core.xml.io.Unmarshaller) UnmarshallingException(org.opensaml.core.xml.io.UnmarshallingException)

Example 72 with Assertion

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

the class TestAttributeQueryClient method testRetrieveResponse.

@Test
public void testRetrieveResponse() {
    setResponse(cannedResponse, false);
    Assertion assertion = attributeQueryClient.query(USERNAME);
    assertThat(assertion, is(notNullValue()));
    assertThat(assertion.getIssuer().getValue(), is(equalTo("localhost")));
    assertThat(assertion.getSubject().getNameID().getValue(), is(equalTo("admin")));
    assertThat(assertion.getAttributeStatements(), is(notNullValue()));
}
Also used : Assertion(org.opensaml.saml.saml2.core.Assertion) Test(org.junit.Test)

Example 73 with Assertion

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

the class SimpleSign method signSamlObject.

public void signSamlObject(SignableSAMLObject samlObject) throws SignatureException {
    X509Certificate[] certificates = getSignatureCertificates();
    String sigAlgo = getSignatureAlgorithm(certificates[0]);
    PrivateKey privateKey = getSignaturePrivateKey();
    // Create the signature
    Signature signature = OpenSAMLUtil.buildSignature();
    if (signature == null) {
        throw new SignatureException("Unable to build signature.");
    }
    signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    signature.setSignatureAlgorithm(sigAlgo);
    BasicX509Credential signingCredential = new BasicX509Credential(certificates[0]);
    signingCredential.setPrivateKey(privateKey);
    signature.setSigningCredential(signingCredential);
    X509KeyInfoGeneratorFactory x509KeyInfoGeneratorFactory = new X509KeyInfoGeneratorFactory();
    x509KeyInfoGeneratorFactory.setEmitEntityCertificate(true);
    try {
        KeyInfo keyInfo = x509KeyInfoGeneratorFactory.newInstance().generate(signingCredential);
        signature.setKeyInfo(keyInfo);
    } catch (org.opensaml.security.SecurityException e) {
        throw new SignatureException("Error generating KeyInfo from signing credential", e);
    }
    if (samlObject instanceof Response) {
        List<Assertion> assertions = ((Response) samlObject).getAssertions();
        for (Assertion assertion : assertions) {
            assertion.getSignature().setSigningCredential(signingCredential);
        }
    }
    samlObject.setSignature(signature);
    SAMLObjectContentReference contentRef = (SAMLObjectContentReference) signature.getContentReferences().get(0);
    contentRef.setDigestAlgorithm(SignatureConstants.ALGO_ID_DIGEST_SHA1);
    samlObject.releaseDOM();
    samlObject.releaseChildrenDOM(true);
}
Also used : PrivateKey(java.security.PrivateKey) Assertion(org.opensaml.saml.saml2.core.Assertion) X509Certificate(java.security.cert.X509Certificate) Response(org.opensaml.saml.saml2.core.Response) BasicX509Credential(org.opensaml.security.x509.BasicX509Credential) KeyInfo(org.opensaml.xmlsec.signature.KeyInfo) SAMLKeyInfo(org.apache.wss4j.common.saml.SAMLKeyInfo) Signature(org.opensaml.xmlsec.signature.Signature) SAMLObjectContentReference(org.opensaml.saml.common.SAMLObjectContentReference) X509KeyInfoGeneratorFactory(org.opensaml.xmlsec.keyinfo.impl.X509KeyInfoGeneratorFactory)

Example 74 with Assertion

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

the class GoogleAccountsServiceResponseBuilder method constructSamlResponse.

/**
 * Construct SAML response.
 * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
 *
 * @param service        the service
 * @param authentication the authentication
 * @return the SAML response
 */
protected String constructSamlResponse(final GoogleAccountsService service, final Authentication authentication) {
    final ZonedDateTime currentDateTime = ZonedDateTime.now(ZoneOffset.UTC);
    final ZonedDateTime notBeforeIssueInstant = ZonedDateTime.parse("2003-04-17T00:46:02Z");
    final RegisteredService registeredService = servicesManager.findServiceBy(service);
    if (registeredService == null || !registeredService.getAccessStrategy().isServiceAccessAllowed()) {
        throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_UNAUTHZ_SERVICE);
    }
    final Principal principal = authentication.getPrincipal();
    final String userId = registeredService.getUsernameAttributeProvider().resolveUsername(principal, service, registeredService);
    final org.opensaml.saml.saml2.core.Response response = this.samlObjectBuilder.newResponse(this.samlObjectBuilder.generateSecureRandomId(), currentDateTime, null, service);
    response.setStatus(this.samlObjectBuilder.newStatus(StatusCode.SUCCESS, null));
    final String sessionIndex = '_' + String.valueOf(Math.abs(RandomUtils.getNativeInstance().nextLong()));
    final AuthnStatement authnStatement = this.samlObjectBuilder.newAuthnStatement(AuthnContext.PASSWORD_AUTHN_CTX, currentDateTime, sessionIndex);
    final Assertion assertion = this.samlObjectBuilder.newAssertion(authnStatement, casServerPrefix, notBeforeIssueInstant, this.samlObjectBuilder.generateSecureRandomId());
    final Conditions conditions = this.samlObjectBuilder.newConditions(notBeforeIssueInstant, currentDateTime.plusSeconds(this.skewAllowance), service.getId());
    assertion.setConditions(conditions);
    final Subject subject = this.samlObjectBuilder.newSubject(NameID.EMAIL, userId, service.getId(), currentDateTime.plusSeconds(this.skewAllowance), service.getRequestId(), null);
    assertion.setSubject(subject);
    response.getAssertions().add(assertion);
    final String result = SamlUtils.transformSamlObject(this.samlObjectBuilder.getConfigBean(), response, true).toString();
    LOGGER.debug("Generated Google SAML response: [{}]", result);
    return result;
}
Also used : RegisteredService(org.apereo.cas.services.RegisteredService) Assertion(org.opensaml.saml.saml2.core.Assertion) UnauthorizedServiceException(org.apereo.cas.services.UnauthorizedServiceException) Conditions(org.opensaml.saml.saml2.core.Conditions) Subject(org.opensaml.saml.saml2.core.Subject) ZonedDateTime(java.time.ZonedDateTime) AuthnStatement(org.opensaml.saml.saml2.core.AuthnStatement) Principal(org.apereo.cas.authentication.principal.Principal)

Example 75 with Assertion

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

the class SamlIdPUtils method preparePeerEntitySamlEndpointContext.

/**
 * Prepare peer entity saml endpoint.
 *
 * @param outboundContext the outbound context
 * @param adaptor         the adaptor
 * @param binding         the binding
 * @throws SamlException the saml exception
 */
public static void preparePeerEntitySamlEndpointContext(final MessageContext outboundContext, final SamlRegisteredServiceServiceProviderMetadataFacade adaptor, final String binding) throws SamlException {
    if (!adaptor.containsAssertionConsumerServices()) {
        throw new SamlException("No assertion consumer service could be found for entity " + adaptor.getEntityId());
    }
    final SAMLPeerEntityContext peerEntityContext = outboundContext.getSubcontext(SAMLPeerEntityContext.class, true);
    if (peerEntityContext == null) {
        throw new SamlException("SAMLPeerEntityContext could not be defined for entity " + adaptor.getEntityId());
    }
    peerEntityContext.setEntityId(adaptor.getEntityId());
    final SAMLEndpointContext endpointContext = peerEntityContext.getSubcontext(SAMLEndpointContext.class, true);
    if (endpointContext == null) {
        throw new SamlException("SAMLEndpointContext could not be defined for entity " + adaptor.getEntityId());
    }
    final Endpoint endpoint = adaptor.getAssertionConsumerService(binding);
    if (StringUtils.isBlank(endpoint.getBinding()) || StringUtils.isBlank(endpoint.getLocation())) {
        throw new SamlException("Assertion consumer service does not define a binding or location for " + adaptor.getEntityId());
    }
    LOGGER.debug("Configured peer entity endpoint to be [{}] with binding [{}]", endpoint.getLocation(), endpoint.getBinding());
    endpointContext.setEndpoint(endpoint);
}
Also used : SAMLEndpointContext(org.opensaml.saml.common.messaging.context.SAMLEndpointContext) Endpoint(org.opensaml.saml.saml2.metadata.Endpoint) SAMLPeerEntityContext(org.opensaml.saml.common.messaging.context.SAMLPeerEntityContext)

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