Java Code Examples for org.opensaml.saml.saml2.core.Assertion#setConditions()

The following examples show how to use org.opensaml.saml.saml2.core.Assertion#setConditions() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
private String createSamlAuthResponse(AuthnRequest authnRequest) {
    try {
        Response response = createSamlElement(Response.class);
        response.setID(nextId());

        if (authnRequest != null) {
            response.setInResponseTo(authnRequest.getID());
        }

        response.setVersion(SAMLVersion.VERSION_20);
        response.setStatus(createStatus(StatusCode.SUCCESS));
        response.setIssueInstant(new DateTime());

        Assertion assertion = createSamlElement(Assertion.class);
        response.getAssertions().add(assertion);

        assertion.setID(nextId());
        assertion.setIssueInstant(new DateTime());
        assertion.setIssuer(createIssuer());

        AuthnStatement authnStatement = createSamlElement(AuthnStatement.class);
        assertion.getAuthnStatements().add(authnStatement);

        authnStatement.setAuthnInstant(new DateTime());
        authnStatement.setSessionIndex(nextId());
        authnStatement.setAuthnContext(createAuthnCotext());

        Subject subject = createSamlElement(Subject.class);
        assertion.setSubject(subject);

        subject.setNameID(createNameID(NameIDType.UNSPECIFIED, authenticateUser));

        if (authnRequest != null) {
            subject.getSubjectConfirmations()
                    .add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                            new DateTime().plusMinutes(1), authnRequest.getID(),
                            authnRequest.getAssertionConsumerServiceURL()));
        } else {
            subject.getSubjectConfirmations().add(createSubjectConfirmation("urn:oasis:names:tc:SAML:2.0:cm:bearer",
                    new DateTime().plusMinutes(1), null, defaultAssertionConsumerService));
        }

        Conditions conditions = createSamlElement(Conditions.class);
        assertion.setConditions(conditions);

        conditions.setNotBefore(new DateTime());
        conditions.setNotOnOrAfter(new DateTime().plusMinutes(1));

        if (authenticateUserRoles != null) {
            AttributeStatement attributeStatement = createSamlElement(AttributeStatement.class);
            assertion.getAttributeStatements().add(attributeStatement);

            Attribute attribute = createSamlElement(Attribute.class);
            attributeStatement.getAttributes().add(attribute);

            attribute.setName("roles");
            attribute.setNameFormat("urn:oasis:names:tc:SAML:2.0:attrname-format:basic");

            for (String role : authenticateUserRoles) {
                attribute.getAttributeValues().add(createXSAny(AttributeValue.DEFAULT_ELEMENT_NAME, role));
            }
        }

        if (signResponses) {
            Signature signature = createSamlElement(Signature.class);
            assertion.setSignature(signature);

            signature.setSigningCredential(this.signingCredential);
            signature.setSignatureAlgorithm(SignatureConstants.ALGO_ID_SIGNATURE_RSA_SHA1);
            signature.setCanonicalizationAlgorithm(SignatureConstants.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);

            XMLObjectProviderRegistrySupport.getMarshallerFactory().getMarshaller(assertion).marshall(assertion);

            Signer.signObject(signature);
        }

        String marshalledXml = marshallSamlXml(response);

        return Base64Support.encode(marshalledXml.getBytes("UTF-8"), Base64Support.UNCHUNKED);

    } catch (MarshallingException | SignatureException | UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}
 
Example 2
Source File: GoogleAccountsService.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Construct SAML response.
 * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
 * @return the SAML response
 */
private String constructSamlResponse() {
    final DateTime currentDateTime = DateTime.parse(new ISOStandardDateFormat().getCurrentDateAndTime());
    final DateTime notBeforeIssueInstant = DateTime.parse("2003-04-17T00:46:02Z");

    final RegisteredService svc = this.servicesManager.findServiceBy(this);
    final String userId = svc.getUsernameAttributeProvider().resolveUsername(getPrincipal(), this);

    final org.opensaml.saml.saml2.core.Response response = BUILDER.newResponse(
            BUILDER.generateSecureRandomId(),
            currentDateTime,
            getId(), this);
    response.setStatus(BUILDER.newStatus(StatusCode.SUCCESS, null));

    final AuthnStatement authnStatement = BUILDER.newAuthnStatement(
            AuthnContext.PASSWORD_AUTHN_CTX, currentDateTime);
    final Assertion assertion = BUILDER.newAssertion(authnStatement,
            "https://www.opensaml.org/IDP",
            notBeforeIssueInstant, BUILDER.generateSecureRandomId());

    final Conditions conditions = BUILDER.newConditions(notBeforeIssueInstant,
            currentDateTime, getId());
    assertion.setConditions(conditions);

    final Subject subject = BUILDER.newSubject(NameID.EMAIL, userId,
            getId(), currentDateTime, this.requestId);
    assertion.setSubject(subject);

    response.getAssertions().add(assertion);

    final StringWriter writer = new StringWriter();
    BUILDER.marshalSamlXmlObject(response, writer);

    final String result = writer.toString();
    logger.debug("Generated Google SAML response: {}", result);
    return result;
}
 
Example 3
Source File: SamlServiceProviderTest.java    From armeria with Apache License 2.0 4 votes vote down vote up
private static Response getAuthResponse(String recipient) throws Exception {
    // IdP entity ID
    final Issuer issuer = build(Issuer.DEFAULT_ELEMENT_NAME);
    issuer.setValue("http://idp.example.com/post");

    final Assertion assertion = build(Assertion.DEFAULT_ELEMENT_NAME);
    final Subject subject = build(Subject.DEFAULT_ELEMENT_NAME);
    final SubjectConfirmation subjectConfirmation = build(SubjectConfirmation.DEFAULT_ELEMENT_NAME);
    final SubjectConfirmationData data = build(SubjectConfirmationData.DEFAULT_ELEMENT_NAME);

    data.setInResponseTo(requestIdManager.newId());
    data.setNotOnOrAfter(DateTime.now().plusMinutes(1));
    data.setRecipient(recipient);

    subjectConfirmation.setSubjectConfirmationData(data);
    subjectConfirmation.setMethod("urn:oasis:names:tc:SAML:2.0:cm:bearer");

    subject.getSubjectConfirmations().add(subjectConfirmation);

    assertion.setSubject(subject);

    assertion.setIssuer(XMLObjectSupport.cloneXMLObject(issuer));
    assertion.setIssueInstant(DateTime.now());
    assertion.setID(requestIdManager.newId());

    final AuthnStatement authnStatement = build(AuthnStatement.DEFAULT_ELEMENT_NAME);
    authnStatement.setSessionIndex("1");
    assertion.getAuthnStatements().add(authnStatement);

    final Conditions conditions = build(Conditions.DEFAULT_ELEMENT_NAME);
    conditions.setNotBefore(DateTime.now().minusMinutes(1));
    conditions.setNotOnOrAfter(DateTime.now().plusMinutes(1));

    final AudienceRestriction audienceRestriction = build(AudienceRestriction.DEFAULT_ELEMENT_NAME);
    final Audience audience = build(Audience.DEFAULT_ELEMENT_NAME);
    // Set SP entity ID as an audience.
    audience.setAudienceURI(spEntityId);
    audienceRestriction.getAudiences().add(audience);
    conditions.getAudienceRestrictions().add(audienceRestriction);

    assertion.setConditions(conditions);

    sign(assertion, idpCredential, signatureAlgorithm);

    final Response response = build(Response.DEFAULT_ELEMENT_NAME);
    response.getAssertions().add(assertion);

    response.setID(requestIdManager.newId());
    response.setIssuer(issuer);
    response.setIssueInstant(DateTime.now());

    final Status status = build(Status.DEFAULT_ELEMENT_NAME);
    final StatusCode statusCode = build(StatusCode.DEFAULT_ELEMENT_NAME);
    statusCode.setValue(StatusCode.SUCCESS);
    status.setStatusCode(statusCode);
    response.setStatus(status);

    return response;
}