org.opensaml.saml.saml2.core.Conditions Java Examples

The following examples show how to use org.opensaml.saml.saml2.core.Conditions. 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: ConditionsValidator.java    From verify-service-provider with MIT License 6 votes vote down vote up
public void validate(Conditions conditionsElement, String... acceptableEntityIds) {
    if (conditionsElement == null) {
        throw new SamlResponseValidationException("Conditions is missing from the assertion.");
    }

    if (conditionsElement.getProxyRestriction() != null) {
        throw new SamlResponseValidationException("Conditions should not contain proxy restriction element.");
    }

    if (conditionsElement.getOneTimeUse() != null) {
        throw new SamlResponseValidationException("Conditions should not contain one time use element.");
    }

    DateTime notOnOrAfter = conditionsElement.getNotOnOrAfter();
    if (notOnOrAfter != null) {
        timeRestrictionValidator.validateNotOnOrAfter(notOnOrAfter);
    }

    timeRestrictionValidator.validateNotBefore(conditionsElement.getNotBefore());
    audienceRestrictionValidator.validate(conditionsElement.getAudienceRestrictions(), acceptableEntityIds);
}
 
Example #2
Source File: ValidatorUtils.java    From saml-client with MIT License 6 votes vote down vote up
/**
 * Enforce conditions.
 *
 * @param conditions the conditions
 * @param _now            the current date time (for unit test only)
 * @param notBeforeSkew  the notBeforeSkew
 * @throws SamlException the saml exception
 */
private static void enforceConditions(Conditions conditions, DateTime _now, long notBeforeSkew)
    throws SamlException {
  DateTime now = _now != null ? _now : DateTime.now();

  DateTime notBefore = conditions.getNotBefore();
  DateTime skewedNotBefore = notBefore.minus(notBeforeSkew);
  if (now.isBefore(skewedNotBefore)) {
    throw new SamlException("The assertion cannot be used before " + notBefore.toString());
  }

  DateTime notOnOrAfter = conditions.getNotOnOrAfter();
  if (now.isAfter(notOnOrAfter)) {
    throw new SamlException("The assertion cannot be used after  " + notOnOrAfter.toString());
  }
}
 
Example #3
Source File: SamlOAuthValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
public void validate(Message message, SamlAssertionWrapper wrapper) {
    validateSAMLVersion(wrapper);

    Conditions cs = wrapper.getSaml2().getConditions();
    validateAudience(message, cs);

    if (issuer != null) {
        String actualIssuer = getIssuer(wrapper);
        String expectedIssuer = OAuthConstants.CLIENT_ID.equals(issuer)
            ? wrapper.getSaml2().getSubject().getNameID().getValue() : issuer;
        if (actualIssuer == null || !actualIssuer.equals(expectedIssuer)) {
            throw ExceptionUtils.toNotAuthorizedException(null, null);
        }
    }
    if (!validateAuthenticationSubject(message, cs, wrapper.getSaml2().getSubject())) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }
}
 
Example #4
Source File: SamlOAuthValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private boolean validateAuthenticationSubject(Message m,
                                              Conditions cs,
                                              org.opensaml.saml.saml2.core.Subject subject) {
    // We need to find a Bearer Subject Confirmation method
    boolean bearerSubjectConfFound = false;
    if (subject.getSubjectConfirmations() != null) {
        for (SubjectConfirmation subjectConf : subject.getSubjectConfirmations()) {
            if (SAML2Constants.CONF_BEARER.equals(subjectConf.getMethod())) {
                validateSubjectConfirmation(m, cs, subjectConf.getSubjectConfirmationData());
                bearerSubjectConfFound = true;
            }
        }
    }

    return bearerSubjectConfFound;
}
 
Example #5
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 #6
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 #7
Source File: AbstractSaml20ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * New conditions element.
 *
 * @param notBefore the not before
 * @param notOnOrAfter the not on or after
 * @param audienceUri the service id
 * @return the conditions
 */
public Conditions newConditions(final DateTime notBefore, final DateTime notOnOrAfter, final String audienceUri) {
    final Conditions conditions = newSamlObject(Conditions.class);
    conditions.setNotBefore(notBefore);
    conditions.setNotOnOrAfter(notOnOrAfter);

    final AudienceRestriction audienceRestriction = newSamlObject(AudienceRestriction.class);
    final Audience audience = newSamlObject(Audience.class);
    audience.setAudienceURI(audienceUri);
    audienceRestriction.getAudiences().add(audience);
    conditions.getAudienceRestrictions().add(audienceRestriction);
    return conditions;
}
 
Example #8
Source File: AssertionHelper.java    From verify-service-provider with MIT License 5 votes vote down vote up
private static Conditions aConditions() {
    Conditions conditions = new ConditionsBuilder().buildObject();
    conditions.setNotBefore(DateTime.now());
    conditions.setNotOnOrAfter(DateTime.now().plusMinutes(10));
    AudienceRestriction audienceRestriction = new AudienceRestrictionBuilder().buildObject();
    Audience audience = new AudienceBuilder().buildObject();
    audience.setAudienceURI(TEST_RP);
    audienceRestriction.getAudiences().add(audience);
    conditions.getAudienceRestrictions().add(audienceRestriction);
    return conditions;
}
 
Example #9
Source File: AssertionHelper.java    From verify-service-provider with MIT License 5 votes vote down vote up
private static Conditions aConditionsForEidas() {
    Conditions conditions = new ConditionsBuilder().buildObject();
    conditions.setNotBefore(DateTime.now());
    conditions.setNotOnOrAfter(DateTime.now().plusMinutes(10));
    AudienceRestriction audienceRestriction = new AudienceRestrictionBuilder().buildObject();
    Audience audience = new AudienceBuilder().buildObject();
    audience.setAudienceURI(HUB_CONNECTOR_ENTITY_ID);
    audienceRestriction.getAudiences().add(audience);
    conditions.getAudienceRestrictions().add(audienceRestriction);
    return conditions;
}
 
Example #10
Source File: AssertionValidatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldValidateAssertionConditions() {
    Conditions conditions = mock(Conditions.class);
    when(assertion.getConditions()).thenReturn(conditions);

    validator.validate(assertion, "any-expected-in-response-to", "some-entity-id");

    verify(conditionsValidator).validate(conditions, "some-entity-id");
}
 
Example #11
Source File: ConditionsValidatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Before
public void setUp() {
    timeRestrictionValidator = mock(TimeRestrictionValidator.class);
    audienceRestrictionValidator = mock(AudienceRestrictionValidator.class);
    conditions = mock(Conditions.class);

    validator = new ConditionsValidator(timeRestrictionValidator, audienceRestrictionValidator);

    IdaSamlBootstrap.bootstrap();
}
 
Example #12
Source File: SamlOAuthValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void validateAudience(Message message, Conditions cs) {
    String absoluteAddress = getAbsoluteTargetAddress(message);

    List<AudienceRestriction> restrictions = cs.getAudienceRestrictions();
    for (AudienceRestriction ar : restrictions) {
        List<Audience> audiences = ar.getAudiences();
        for (Audience a : audiences) {
            if (absoluteAddress.equals(a.getAudienceURI())) {
                return;
            }
        }
    }
    throw ExceptionUtils.toNotAuthorizedException(null, null);
}
 
Example #13
Source File: SamlOAuthValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
/**
   * Validate a (Bearer) Subject Confirmation
   */
private void validateSubjectConfirmation(Message m,
                                         Conditions cs,
                                         SubjectConfirmationData subjectConfData) {
    if (subjectConfData == null) {
        if (!subjectConfirmationDataRequired
            && cs.getNotOnOrAfter() != null && !cs.getNotOnOrAfter().isBeforeNow()) {
            return;
        }
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }

    // Recipient must match assertion consumer URL
    String recipient = subjectConfData.getRecipient();
    if (recipient == null || !recipient.equals(getAbsoluteTargetAddress(m))) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }

    // We must have a NotOnOrAfter timestamp
    if (subjectConfData.getNotOnOrAfter() == null
        || subjectConfData.getNotOnOrAfter().isBeforeNow()) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }

    //TODO: replay cache, same as with SAML SSO case

    // Check address
    if (subjectConfData.getAddress() != null
        && (clientAddress == null || !subjectConfData.getAddress().equals(clientAddress))) {
        throw ExceptionUtils.toNotAuthorizedException(null, null);
    }


}
 
Example #14
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;
}