Search in sources :

Example 31 with Assertion

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

the class SAML2LoginAPIAuthenticatorCmdTest method buildMockResponse.

private Response buildMockResponse() throws Exception {
    Response samlMessage = new ResponseBuilder().buildObject();
    samlMessage.setID("foo");
    samlMessage.setVersion(SAMLVersion.VERSION_20);
    samlMessage.setIssueInstant(new DateTime(0));
    Issuer issuer = new IssuerBuilder().buildObject();
    issuer.setValue("MockedIssuer");
    samlMessage.setIssuer(issuer);
    Status status = new StatusBuilder().buildObject();
    StatusCode statusCode = new StatusCodeBuilder().buildObject();
    statusCode.setValue(StatusCode.SUCCESS_URI);
    status.setStatusCode(statusCode);
    samlMessage.setStatus(status);
    Assertion assertion = new AssertionBuilder().buildObject();
    Subject subject = new SubjectBuilder().buildObject();
    NameID nameID = new NameIDBuilder().buildObject();
    nameID.setValue("SOME-UNIQUE-ID");
    nameID.setFormat(NameIDType.PERSISTENT);
    subject.setNameID(nameID);
    assertion.setSubject(subject);
    AuthnStatement authnStatement = new AuthnStatementBuilder().buildObject();
    authnStatement.setSessionIndex("Some Session String");
    assertion.getAuthnStatements().add(authnStatement);
    AttributeStatement attributeStatement = new AttributeStatementBuilder().buildObject();
    assertion.getAttributeStatements().add(attributeStatement);
    samlMessage.getAssertions().add(assertion);
    return samlMessage;
}
Also used : Status(org.opensaml.saml2.core.Status) AttributeStatementBuilder(org.opensaml.saml2.core.impl.AttributeStatementBuilder) StatusCodeBuilder(org.opensaml.saml2.core.impl.StatusCodeBuilder) Issuer(org.opensaml.saml2.core.Issuer) NameID(org.opensaml.saml2.core.NameID) Assertion(org.opensaml.saml2.core.Assertion) AssertionBuilder(org.opensaml.saml2.core.impl.AssertionBuilder) AuthnStatementBuilder(org.opensaml.saml2.core.impl.AuthnStatementBuilder) StatusCode(org.opensaml.saml2.core.StatusCode) DateTime(org.joda.time.DateTime) Subject(org.opensaml.saml2.core.Subject) Response(org.opensaml.saml2.core.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) NameIDBuilder(org.opensaml.saml2.core.impl.NameIDBuilder) AttributeStatement(org.opensaml.saml2.core.AttributeStatement) AuthnStatement(org.opensaml.saml2.core.AuthnStatement) StatusBuilder(org.opensaml.saml2.core.impl.StatusBuilder) IssuerBuilder(org.opensaml.saml2.core.impl.IssuerBuilder) ResponseBuilder(org.opensaml.saml2.core.impl.ResponseBuilder) SubjectBuilder(org.opensaml.saml2.core.impl.SubjectBuilder)

Example 32 with Assertion

use of org.opensaml.saml.saml1.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 33 with Assertion

use of org.opensaml.saml.saml1.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 34 with Assertion

use of org.opensaml.saml.saml1.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 35 with Assertion

use of org.opensaml.saml.saml1.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)

Aggregations

Assertion (org.opensaml.saml.saml2.core.Assertion)33 Test (org.junit.Test)16 Assertion (org.opensaml.saml.saml1.core.Assertion)13 AssertionBuilder.anAssertion (uk.gov.ida.saml.core.test.builders.AssertionBuilder.anAssertion)9 Response (org.opensaml.saml.saml2.core.Response)8 DateTime (org.joda.time.DateTime)6 Assertion (org.opensaml.saml2.core.Assertion)6 Element (org.w3c.dom.Element)6 PassthroughAssertion (uk.gov.ida.saml.core.domain.PassthroughAssertion)6 Subject (org.opensaml.saml.saml2.core.Subject)5 MetricRegistry (com.codahale.metrics.MetricRegistry)4 ZonedDateTime (java.time.ZonedDateTime)4 ArrayList (java.util.ArrayList)4 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)4 SamlAssertionWrapper (org.apache.wss4j.common.saml.SamlAssertionWrapper)4 Credential (org.apache.wss4j.dom.validate.Credential)4 Service (org.apereo.cas.authentication.principal.Service)4 RegisteredService (org.apereo.cas.services.RegisteredService)4 WsFederationCredential (org.apereo.cas.support.wsfederation.authentication.principal.WsFederationCredential)4 XMLObject (org.opensaml.core.xml.XMLObject)4