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

The following examples show how to use org.opensaml.saml.saml2.core.AuthnStatement. 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: AssertionValidatorTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Before
public void setUp() {
    instantValidator = mock(InstantValidator.class);
    subjectValidator = mock(SubjectValidator.class);
    conditionsValidator = mock(ConditionsValidator.class);
    assertion = mock(Assertion.class);
    AuthnStatement authnStatement = mock(AuthnStatement.class);

    validator = new AssertionValidator(
        instantValidator,
        subjectValidator,
        conditionsValidator
    );

    when(assertion.getAuthnStatements()).thenReturn(ImmutableList.of(authnStatement));

    IdaSamlBootstrap.bootstrap();
}
 
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: SamlAssertionConsumerFunction.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse serve(ServiceRequestContext ctx, AggregatedHttpRequest req,
                          String defaultHostname, SamlPortConfig portConfig) {
    try {
        final MessageContext<Response> messageContext;
        if (cfg.endpoint().bindingProtocol() == SamlBindingProtocol.HTTP_REDIRECT) {
            messageContext = HttpRedirectBindingUtil.toSamlObject(req, SAML_RESPONSE,
                                                                  idpConfigs, defaultIdpConfig);
        } else {
            messageContext = HttpPostBindingUtil.toSamlObject(req, SAML_RESPONSE);
        }

        final String endpointUri = cfg.endpoint().toUriString(portConfig.scheme().uriText(),
                                                              defaultHostname, portConfig.port());
        final Response response = messageContext.getMessage();
        final Assertion assertion = getValidatedAssertion(response, endpointUri);

        // Find a session index which is sent by an identity provider.
        final String sessionIndex = assertion.getAuthnStatements().stream()
                                             .map(AuthnStatement::getSessionIndex)
                                             .filter(Objects::nonNull)
                                             .findFirst().orElse(null);

        final SAMLBindingContext bindingContext = messageContext.getSubcontext(SAMLBindingContext.class);
        final String relayState = bindingContext != null ? bindingContext.getRelayState() : null;

        return ssoHandler.loginSucceeded(ctx, req, messageContext, sessionIndex, relayState);
    } catch (SamlException e) {
        return ssoHandler.loginFailed(ctx, req, null, e);
    }
}
 
Example #4
Source File: MatchingAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionWhenLevelOfAssuranceNotPresent() {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Expected a level of assurance.");

    AuthnStatement authnStatement = anAuthnStatement().withAuthnContext(
        anAuthnContext().withAuthnContextClassRef(null).build())
        .build();
    Assertion assertion = aSignedAssertion()
        .addAuthnStatement(authnStatement
        ).buildUnencrypted();

    msaAssertionTranslator.translateSuccessResponse(ImmutableList.of(assertion), IN_RESPONSE_TO, LEVEL_2, VERIFY_SERVICE_PROVIDER_ENTITY_ID);
}
 
Example #5
Source File: MatchingAssertionTranslator.java    From verify-service-provider with MIT License 5 votes vote down vote up
private LevelOfAssurance extractLevelOfAssurance(AuthnStatement authnStatement) {
    String levelOfAssuranceString = ofNullable(authnStatement.getAuthnContext())
        .map(AuthnContext::getAuthnContextClassRef)
        .map(AuthnContextClassRef::getAuthnContextClassRef)
        .orElseThrow(() -> new SamlResponseValidationException("Expected a level of assurance."));

    try {
        return LevelOfAssurance.fromSamlValue(levelOfAssuranceString);
    } catch (Exception ex) {
        throw new SamlResponseValidationException(String.format("Level of assurance '%s' is not supported.", levelOfAssuranceString));
    }
}
 
Example #6
Source File: MatchingAssertionTranslator.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Override
public TranslatedResponseBody translateSuccessResponse(
        List<Assertion> assertions,
        String expectedInResponseTo,
        LevelOfAssurance expectedLevelOfAssurance,
        String entityId
) {
    //  1. check saml has assertions
    checkSamlhasAssertions(assertions);
    //  2. validate assertions
    Assertion assertion = assertions.get(0);
    assertionValidator.validate(assertion, expectedInResponseTo, entityId);
    assertionsSignatureValidator.validate(assertions, IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
    //  3. validate levelOfAssurance
    AuthnStatement authnStatement = assertion.getAuthnStatements().get(0);
    LevelOfAssurance levelOfAssurance = extractLevelOfAssurance(authnStatement);
    levelOfAssuranceValidator.validate(levelOfAssurance, expectedLevelOfAssurance);
    //  4. translateAssertions
    String nameID = assertion.getSubject().getNameID().getValue();
    List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
    if (isUserAccountCreation(attributeStatements)) {
        return new TranslatedMatchingResponseBody(
            ACCOUNT_CREATION,
            nameID,
            levelOfAssurance,
            AttributeTranslator.translateAttributes(attributeStatements.get(0))
        );

    }
    return new TranslatedMatchingResponseBody(SUCCESS_MATCH, nameID, levelOfAssurance, null);

}
 
Example #7
Source File: IdentityAssertionTranslator.java    From verify-service-provider with MIT License 5 votes vote down vote up
String extractLevelOfAssuranceUriFrom(Assertion assertion) {
    AuthnStatement authnStatement = getAuthnStatementFrom(assertion);
    return ofNullable(authnStatement.getAuthnContext())
            .map(AuthnContext::getAuthnContextClassRef)
            .map(AuthnContextClassRef::getAuthnContextClassRef)
            .orElseThrow(() -> new SamlResponseValidationException("Expected a level of assurance."));
}
 
Example #8
Source File: AbstractSaml20ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * New authn statement.
 *
 * @param contextClassRef the context class ref such as {@link AuthnContext#PASSWORD_AUTHN_CTX}
 * @param authnInstant the authn instant
 * @return the authn statement
 */
public AuthnStatement newAuthnStatement(final String contextClassRef, final DateTime authnInstant) {
    final AuthnStatement stmt = newSamlObject(AuthnStatement.class);
    final AuthnContext ctx = newSamlObject(AuthnContext.class);

    final AuthnContextClassRef classRef = newSamlObject(AuthnContextClassRef.class);
    classRef.setAuthnContextClassRef(contextClassRef);

    ctx.setAuthnContextClassRef(classRef);
    stmt.setAuthnContext(ctx);
    stmt.setAuthnInstant(authnInstant);

    return stmt;
}
 
Example #9
Source File: AbstractSaml20ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 5 votes vote down vote up
/**
 * Create a new SAML1 response object.
 *
 * @param authnStatement the authn statement
 * @param issuer the issuer
 * @param issuedAt the issued at
 * @param id the id
 * @return the assertion
 */
public Assertion newAssertion(final AuthnStatement authnStatement, final String issuer,
                              final DateTime issuedAt, final String id) {
    final Assertion assertion = newSamlObject(Assertion.class);
    assertion.setID(id);
    assertion.setIssueInstant(issuedAt);
    assertion.setIssuer(newIssuer(issuer));
    assertion.getAuthnStatements().add(authnStatement);
    return assertion;
}
 
Example #10
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 #11
Source File: IdentityAssertionTranslator.java    From verify-service-provider with MIT License 4 votes vote down vote up
private AuthnStatement getAuthnStatementFrom(Assertion assertion) {
    return assertion.getAuthnStatements().get(0);
}
 
Example #12
Source File: AssertionValidator.java    From verify-service-provider with MIT License 4 votes vote down vote up
private void validateAuthnStatements(List<AuthnStatement> authnStatements) {
    if (authnStatements == null || authnStatements.size() != 1) {
        throw new SamlResponseValidationException("Exactly one authn statement is expected.");
    }
}
 
Example #13
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 #14
Source File: SAMLSSOResponseValidator.java    From cxf with Apache License 2.0 4 votes vote down vote up
/**
 * Validate a SAML 2 Protocol Response
 * @param samlResponse
 * @param postBinding
 * @return a SSOValidatorResponse object
 * @throws WSSecurityException
 */
public SSOValidatorResponse validateSamlResponse(
    org.opensaml.saml.saml2.core.Response samlResponse,
    boolean postBinding
) throws WSSecurityException {
    // Check the Issuer
    validateIssuer(samlResponse.getIssuer());

    // The Response must contain at least one Assertion.
    if (samlResponse.getAssertions() == null || samlResponse.getAssertions().isEmpty()) {
        LOG.warning("The Response must contain at least one Assertion");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // The Response must contain a Destination that matches the assertionConsumerURL if it is
    // signed
    String destination = samlResponse.getDestination();
    if (samlResponse.isSigned()
        && (destination == null || !destination.equals(assertionConsumerURL))) {
        LOG.warning("The Response must contain a destination that matches the assertion consumer URL");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    if (enforceResponseSigned && !samlResponse.isSigned()) {
        LOG.warning("The Response must be signed!");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // Validate Assertions
    org.opensaml.saml.saml2.core.Assertion validAssertion = null;
    Instant sessionNotOnOrAfter = null;
    for (org.opensaml.saml.saml2.core.Assertion assertion : samlResponse.getAssertions()) {
        // Check the Issuer
        if (assertion.getIssuer() == null) {
            LOG.warning("Assertion Issuer must not be null");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
        }
        validateIssuer(assertion.getIssuer());

        if (!samlResponse.isSigned() && enforceAssertionsSigned && assertion.getSignature() == null) {
            LOG.warning("The enclosed assertions in the SAML Response must be signed");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
        }

        // Check for AuthnStatements and validate the Subject accordingly
        if (assertion.getAuthnStatements() != null
            && !assertion.getAuthnStatements().isEmpty()) {
            org.opensaml.saml.saml2.core.Subject subject = assertion.getSubject();
            org.opensaml.saml.saml2.core.SubjectConfirmation subjectConf =
                validateAuthenticationSubject(subject, assertion.getID(), postBinding);
            if (subjectConf != null) {
                validateAudienceRestrictionCondition(assertion.getConditions());
                validAssertion = assertion;
                sessionNotOnOrAfter = null;

                // Store Session NotOnOrAfter
                for (AuthnStatement authnStatment : assertion.getAuthnStatements()) {
                    if (authnStatment.getSessionNotOnOrAfter() != null) {
                        sessionNotOnOrAfter =
                            Instant.ofEpochMilli(authnStatment.getSessionNotOnOrAfter().toDate().getTime());
                    }
                }
                // Fall back to the SubjectConfirmationData NotOnOrAfter if we have no session NotOnOrAfter
                if (sessionNotOnOrAfter == null) {
                    sessionNotOnOrAfter =
                        Instant.ofEpochMilli(subjectConf.getSubjectConfirmationData()
                                             .getNotOnOrAfter().toDate().getTime());
                }
            }
        }
    }

    if (validAssertion == null) {
        LOG.warning("The Response did not contain any Authentication Statement that matched "
                 + "the Subject Confirmation criteria");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    SSOValidatorResponse validatorResponse = new SSOValidatorResponse();
    validatorResponse.setResponseId(samlResponse.getID());
    validatorResponse.setSessionNotOnOrAfter(sessionNotOnOrAfter);
    if (samlResponse.getIssueInstant() != null) {
        validatorResponse.setCreated(Instant.ofEpochMilli(samlResponse.getIssueInstant().toDate().getTime()));
    }

    Element assertionElement = validAssertion.getDOM();
    Element clonedAssertionElement = (Element)assertionElement.cloneNode(true);
    validatorResponse.setAssertionElement(clonedAssertionElement);
    validatorResponse.setAssertion(DOM2Writer.nodeToString(clonedAssertionElement));
    validatorResponse.setOpensamlAssertion(validAssertion);

    return validatorResponse;
}
 
Example #15
Source File: SAMLSSOResponseValidatorTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
private Response createResponse(
    SubjectConfirmationDataBean subjectConfirmationData,
    List<AudienceRestrictionBean> audienceRestrictions,
    String authnClassRef
) throws Exception {
    Document doc = DOMUtils.createDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            SAMLProtocolResponseValidator.SAML2_STATUSCODE_SUCCESS, null
        );
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(
            "http://cxf.apache.org/saml", "http://cxf.apache.org/issuer", status
        );

    // Create an AuthenticationAssertion
    SAML2CallbackHandler callbackHandler = new SAML2CallbackHandler();
    callbackHandler.setStatement(SAML2CallbackHandler.Statement.AUTHN);
    callbackHandler.setIssuer("http://cxf.apache.org/issuer");
    callbackHandler.setConfirmationMethod(SAML2Constants.CONF_BEARER);

    callbackHandler.setSubjectConfirmationData(subjectConfirmationData);

    ConditionsBean conditions = new ConditionsBean();
    conditions.setNotBefore(new DateTime());
    conditions.setNotAfter(new DateTime().plusMinutes(5));

    if (audienceRestrictions == null) {
        AudienceRestrictionBean audienceRestriction = new AudienceRestrictionBean();
        audienceRestriction.setAudienceURIs(Collections.singletonList("http://service.apache.org"));
        conditions.setAudienceRestrictions(Collections.singletonList(audienceRestriction));
    } else {
        conditions.setAudienceRestrictions(audienceRestrictions);
    }
    callbackHandler.setConditions(conditions);

    SAMLCallback samlCallback = new SAMLCallback();
    SAMLUtil.doSAMLCallback(callbackHandler, samlCallback);
    SamlAssertionWrapper assertion = new SamlAssertionWrapper(samlCallback);

    response.getAssertions().add(assertion.getSaml2());

    if (authnClassRef != null) {
        AuthnStatement authnStatement =
            response.getAssertions().get(0).getAuthnStatements().get(0);
        authnStatement.getAuthnContext().setAuthnContextClassRef(
            SAML2PResponseComponentBuilder.createAuthnContextClassRef(authnClassRef));
    }

    Element policyElement = OpenSAMLUtil.toDom(response, doc);
    doc.appendChild(policyElement);
    assertNotNull(policyElement);

    return (Response)OpenSAMLUtil.fromDom(policyElement);
}
 
Example #16
Source File: SAMLSSOResponseValidator.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
/**
 * Validate a SAML 2 Protocol Response
 * @param samlResponse
 * @param postBinding
 * @return a SSOValidatorResponse object
 * @throws WSSecurityException
 */
public SSOValidatorResponse validateSamlResponse(
    org.opensaml.saml.saml2.core.Response samlResponse,
    boolean postBinding
) throws WSSecurityException {
    // Check the Issuer
    validateIssuer(samlResponse.getIssuer());

    // The Response must contain at least one Assertion.
    if (samlResponse.getAssertions() == null || samlResponse.getAssertions().isEmpty()) {
        LOG.debug("The Response must contain at least one Assertion");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // The Response must contain a Destination that matches the assertionConsumerURL if it is
    // signed
    String destination = samlResponse.getDestination();
    if (samlResponse.isSigned()
        && (destination == null || !destination.equals(assertionConsumerURL))) {
        LOG.debug("The Response must contain a destination that matches the assertion consumer URL");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    if (enforceResponseSigned && !samlResponse.isSigned()) {
        LOG.debug("The Response must be signed!");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    // Validate Assertions
    org.opensaml.saml.saml2.core.Assertion validAssertion = null;
    Instant sessionNotOnOrAfter = null;
    for (org.opensaml.saml.saml2.core.Assertion assertion : samlResponse.getAssertions()) {
        // Check the Issuer
        if (assertion.getIssuer() == null) {
            LOG.debug("Assertion Issuer must not be null");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
        }
        validateIssuer(assertion.getIssuer());

        if (!samlResponse.isSigned() && enforceAssertionsSigned && assertion.getSignature() == null) {
            LOG.debug("The enclosed assertions in the SAML Response must be signed");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
        }

        // Check for AuthnStatements and validate the Subject accordingly
        if (assertion.getAuthnStatements() != null
            && !assertion.getAuthnStatements().isEmpty()) {
            org.opensaml.saml.saml2.core.Subject subject = assertion.getSubject();
            if (validateAuthenticationSubject(subject, assertion.getID(), postBinding)) {
                validateAudienceRestrictionCondition(assertion.getConditions());
                validAssertion = assertion;
                // Store Session NotOnOrAfter
                for (AuthnStatement authnStatment : assertion.getAuthnStatements()) {
                    if (authnStatment.getSessionNotOnOrAfter() != null) {
                        sessionNotOnOrAfter = authnStatment.getSessionNotOnOrAfter().toDate().toInstant();
                    }
                }
            }
        }

    }

    if (validAssertion == null) {
        LOG.debug("The Response did not contain any Authentication Statement that matched "
                 + "the Subject Confirmation criteria");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    SSOValidatorResponse validatorResponse = new SSOValidatorResponse();
    validatorResponse.setResponseId(samlResponse.getID());
    validatorResponse.setSessionNotOnOrAfter(sessionNotOnOrAfter);

    Element assertionElement = validAssertion.getDOM();
    Element clonedAssertionElement = (Element)assertionElement.cloneNode(true);
    validatorResponse.setAssertionElement(clonedAssertionElement);
    validatorResponse.setAssertion(DOM2Writer.nodeToString(clonedAssertionElement));

    return validatorResponse;
}
 
Example #17
Source File: DefaultSAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Override
public LogoutRequest createLogoutRequest(
    String issuerId,
    String reason,
    SamlAssertionWrapper authenticatedAssertion
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameID nameID = null;
    List<String> sessionIndices = new ArrayList<>();

    if (authenticatedAssertion != null) {
        if (authenticatedAssertion.getSaml2() != null) {
            org.opensaml.saml.saml2.core.Subject subject =
                authenticatedAssertion.getSaml2().getSubject();
            if (subject != null && subject.getNameID() != null) {
                nameID = subject.getNameID();
            }
        }

        if (nameID != null) {
            nameID.detach();
        }

        List<AuthnStatement> authnStatements =
            authenticatedAssertion.getSaml2().getAuthnStatements();
        if (authnStatements != null && !authnStatements.isEmpty()) {
            for (AuthnStatement authnStatement : authnStatements) {
                if (authnStatement.getSessionIndex() != null) {
                    sessionIndices.add(authnStatement.getSessionIndex());
                }
            }
        }
    }

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createLogoutRequest(
        issuer,
        reason,
        nameID,
        sessionIndices
    );
}
 
Example #18
Source File: CustomSAMLPRequestBuilder.java    From cxf-fediz with Apache License 2.0 4 votes vote down vote up
@Override
public LogoutRequest createLogoutRequest(
    String issuerId,
    String reason,
    SamlAssertionWrapper authenticatedAssertion
) throws Exception {
    Issuer issuer =
        SamlpRequestComponentBuilder.createIssuer(issuerId);

    NameID nameID = null;
    List<String> sessionIndices = new ArrayList<>();

    if (authenticatedAssertion != null) {
        if (authenticatedAssertion.getSaml2() != null) {
            org.opensaml.saml.saml2.core.Subject subject =
                authenticatedAssertion.getSaml2().getSubject();
            if (subject != null && subject.getNameID() != null) {
                nameID = subject.getNameID();
            }
        }

        if (nameID != null) {
            nameID.detach();
        }

        List<AuthnStatement> authnStatements =
            authenticatedAssertion.getSaml2().getAuthnStatements();
        if (authnStatements != null && !authnStatements.isEmpty()) {
            for (AuthnStatement authnStatement : authnStatements) {
                if (authnStatement.getSessionIndex() != null) {
                    sessionIndices.add(authnStatement.getSessionIndex());
                }
            }
        }
    }

    //CHECKSTYLE:OFF
    return SamlpRequestComponentBuilder.createLogoutRequest(
        issuer,
        reason,
        nameID,
        sessionIndices
    );
}