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

The following examples show how to use org.opensaml.saml.saml2.core.AudienceRestriction. 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: SAMLTokenRenewer.java    From cxf with Apache License 2.0 6 votes vote down vote up
private boolean matchSaml2AudienceRestriction(
    String appliesTo, List<AudienceRestriction> audienceRestrictions
) {
    boolean found = false;
    if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
        for (AudienceRestriction audienceRestriction : audienceRestrictions) {
            if (audienceRestriction.getAudiences() != null) {
                for (org.opensaml.saml.saml2.core.Audience audience : audienceRestriction.getAudiences()) {
                    if (appliesTo.equals(audience.getAudienceURI())) {
                        return true;
                    }
                }
            }
        }
    }

    return found;
}
 
Example #2
Source File: SAMLSSOResponseValidator.java    From cxf with Apache License 2.0 6 votes vote down vote up
private boolean matchSaml2AudienceRestriction(
    String appliesTo, List<AudienceRestriction> audienceRestrictions
) {
    boolean oneMatchFound = false;
    if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
        for (AudienceRestriction audienceRestriction : audienceRestrictions) {
            if (audienceRestriction.getAudiences() != null) {
                boolean matchFound = false;
                for (org.opensaml.saml.saml2.core.Audience audience : audienceRestriction.getAudiences()) {
                    if (appliesTo.equals(audience.getAudienceURI())) {
                        matchFound = true;
                        oneMatchFound = true;
                        break;
                    }
                }
                if (!matchFound) {
                    return false;
                }
            }
        }
    }

    return oneMatchFound;
}
 
Example #3
Source File: SAMLSSOResponseValidator.java    From cxf-fediz with Apache License 2.0 6 votes vote down vote up
private boolean matchSaml2AudienceRestriction(
    String appliesTo, List<AudienceRestriction> audienceRestrictions
) {
    boolean found = false;
    if (audienceRestrictions != null && !audienceRestrictions.isEmpty()) {
        for (AudienceRestriction audienceRestriction : audienceRestrictions) {
            if (audienceRestriction.getAudiences() != null) {
                for (org.opensaml.saml.saml2.core.Audience audience : audienceRestriction.getAudiences()) {
                    if (appliesTo.equals(audience.getAudienceURI())) {
                        return true;
                    }
                }
            }
        }
    }

    return found;
}
 
Example #4
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 #5
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 #6
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 #7
Source File: ConditionsValidatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldValidateConditionsAudienceRestrictions() {
    List<AudienceRestriction> audienceRestrictions = ImmutableList.of(anAudienceRestriction().build());
    when(conditions.getAudienceRestrictions()).thenReturn(audienceRestrictions);

    validator.validate(conditions, "some-entity-id");

    verify(audienceRestrictionValidator).validate(audienceRestrictions, "some-entity-id");
}
 
Example #8
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 #9
Source File: SAMLSSOResponseValidator.java    From cxf with Apache License 2.0 5 votes vote down vote up
private void validateAudienceRestrictionCondition(
    org.opensaml.saml.saml2.core.Conditions conditions
) throws WSSecurityException {
    if (conditions == null) {
        LOG.warning("Conditions are null");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    List<AudienceRestriction> audienceRestrs = conditions.getAudienceRestrictions();
    if (!matchSaml2AudienceRestriction(spIdentifier, audienceRestrs)) {
        LOG.warning("Assertion does not contain unique subject provider identifier "
                 + spIdentifier + " in the audience restriction conditions");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
}
 
Example #10
Source File: SAMLSSOResponseValidator.java    From cxf-fediz with Apache License 2.0 5 votes vote down vote up
private void validateAudienceRestrictionCondition(
    org.opensaml.saml.saml2.core.Conditions conditions
) throws WSSecurityException {
    if (conditions == null) {
        LOG.debug("Conditions are null");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    List<AudienceRestriction> audienceRestrs = conditions.getAudienceRestrictions();
    if (spIdentifier != null && !matchSaml2AudienceRestriction(spIdentifier, audienceRestrs)) {
        LOG.debug("Assertion does not contain unique subject provider identifier "
                 + spIdentifier + " in the audience restriction conditions");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
}
 
Example #11
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;
}
 
Example #12
Source File: SAMLTokenRenewer.java    From cxf with Apache License 2.0 4 votes vote down vote up
private void validateAssertion(
    SamlAssertionWrapper assertion,
    ReceivedToken tokenToRenew,
    SecurityToken token,
    TokenRenewerParameters tokenParameters
) throws WSSecurityException {
    // Check the cached renewal properties
    Map<String, Object> props = token.getProperties();
    if (props == null) {
        LOG.log(Level.WARNING, "Error in getting properties from cached token");
        throw new STSException(
            "Error in getting properties from cached token", STSException.REQUEST_FAILED
        );
    }
    String isAllowRenewal = (String)props.get(STSConstants.TOKEN_RENEWING_ALLOW);
    String isAllowRenewalAfterExpiry =
        (String)props.get(STSConstants.TOKEN_RENEWING_ALLOW_AFTER_EXPIRY);

    if (isAllowRenewal == null || !Boolean.valueOf(isAllowRenewal)) {
        LOG.log(Level.WARNING, "The token is not allowed to be renewed");
        throw new STSException("The token is not allowed to be renewed", STSException.REQUEST_FAILED);
    }

    // Check to see whether the token has expired greater than the configured max expiry time
    if (tokenToRenew.getState() == STATE.EXPIRED) {
        if (!allowRenewalAfterExpiry || isAllowRenewalAfterExpiry == null
            || !Boolean.valueOf(isAllowRenewalAfterExpiry)) {
            LOG.log(Level.WARNING, "Renewal after expiry is not allowed");
            throw new STSException(
                "Renewal after expiry is not allowed", STSException.REQUEST_FAILED
            );
        }
        DateTime expiryDate = getExpiryDate(assertion);
        DateTime currentDate = new DateTime();
        if ((currentDate.getMillis() - expiryDate.getMillis()) > (maxExpiry * 1000L)) {
            LOG.log(Level.WARNING, "The token expired too long ago to be renewed");
            throw new STSException(
                "The token expired too long ago to be renewed", STSException.REQUEST_FAILED
            );
        }
    }

    // Verify Proof of Possession
    ProofOfPossessionValidator popValidator = new ProofOfPossessionValidator();
    if (verifyProofOfPossession) {
        STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
        Crypto sigCrypto = stsProperties.getSignatureCrypto();
        CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
        RequestData requestData = new RequestData();
        requestData.setSigVerCrypto(sigCrypto);
        WSSConfig wssConfig = WSSConfig.getNewInstance();
        requestData.setWssConfig(wssConfig);

        WSDocInfo docInfo = new WSDocInfo(((Element)tokenToRenew.getToken()).getOwnerDocument());
        requestData.setWsDocInfo(docInfo);
        // Parse the HOK subject if it exists

        assertion.parseSubject(
            new WSSSAMLKeyInfoProcessor(requestData), sigCrypto, callbackHandler
        );

        SAMLKeyInfo keyInfo = assertion.getSubjectKeyInfo();
        if (keyInfo == null) {
            keyInfo = new SAMLKeyInfo((byte[])null);
        }
        if (!popValidator.checkProofOfPossession(tokenParameters, keyInfo)) {
            throw new STSException(
                "Failed to verify the proof of possession of the key associated with the "
                + "saml token. No matching key found in the request.",
                STSException.INVALID_REQUEST
            );
        }
    }

    // Check the AppliesTo address
    String appliesToAddress = tokenParameters.getAppliesToAddress();
    if (appliesToAddress != null) {
        if (assertion.getSaml1() != null) {
            List<AudienceRestrictionCondition> restrConditions =
                assertion.getSaml1().getConditions().getAudienceRestrictionConditions();
            if (!matchSaml1AudienceRestriction(appliesToAddress, restrConditions)) {
                LOG.log(Level.WARNING, "The AppliesTo address does not match the Audience Restriction");
                throw new STSException(
                    "The AppliesTo address does not match the Audience Restriction",
                    STSException.INVALID_REQUEST
                );
            }
        } else {
            List<AudienceRestriction> audienceRestrs =
                assertion.getSaml2().getConditions().getAudienceRestrictions();
            if (!matchSaml2AudienceRestriction(appliesToAddress, audienceRestrs)) {
                LOG.log(Level.WARNING, "The AppliesTo address does not match the Audience Restriction");
                throw new STSException(
                    "The AppliesTo address does not match the Audience Restriction",
                    STSException.INVALID_REQUEST
                );
            }
        }
    }

}