Java Code Examples for org.opensaml.saml.saml2.core.Response

The following examples show how to use org.opensaml.saml.saml2.core.Response. These examples are extracted from open source projects. 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
/**
 * Create a new SAML response object.
 * @param id the id
 * @param issueInstant the issue instant
 * @param recipient the recipient
 * @param service the service
 * @return the response
 */
public Response newResponse(final String id, final DateTime issueInstant,
                            final String recipient, final WebApplicationService service) {

    final Response samlResponse = newSamlObject(Response.class);
    samlResponse.setID(id);
    samlResponse.setIssueInstant(issueInstant);
    samlResponse.setVersion(SAMLVersion.VERSION_20);
    if (service instanceof SamlService) {
        final SamlService samlService = (SamlService) service;

        final String requestId = samlService.getRequestID();
        if (StringUtils.isNotBlank(requestId)) {
            samlResponse.setInResponseTo(requestId);
        }
    }
    return samlResponse;
}
 
Example 2
Source Project: centraldogma   Source File: SamlAuthSsoHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private String findLoginNameFromAttributes(Response response) {
    if (Strings.isNullOrEmpty(attributeLoginName)) {
        return null;
    }
    return response.getAssertions()
                   .stream()
                   .flatMap(s -> s.getAttributeStatements().stream())
                   .flatMap(s -> s.getAttributes().stream())
                   .filter(attr -> attr.getName().equals(attributeLoginName))
                   .findFirst()
                   .map(attr -> {
                       final XMLObject v = attr.getAttributeValues().get(0);
                       if (v instanceof XSString) {
                           return ((XSString) v).getValue();
                       } else {
                           return null;
                       }
                   })
                   .orElse(null);
}
 
Example 3
Source Project: verify-service-provider   Source File: ResponseService.java    License: MIT License 6 votes vote down vote up
public ResponseService(
        StringToOpenSamlObjectTransformer<Response> samlObjectTransformer,
        AssertionDecrypter assertionDecrypter,
        AssertionTranslator assertionTranslator,
        SamlResponseSignatureValidator responseSignatureValidator,
        InstantValidator instantValidator,
        ResponderCodeTranslator responderCodeTranslator,
        UnsignedAssertionsResponseHandler unsignedAssertionsResponseHandler
) {
    this.samlObjectTransformer = samlObjectTransformer;
    this.assertionDecrypter = assertionDecrypter;
    this.assertionTranslator = assertionTranslator;
    this.responseSignatureValidator = responseSignatureValidator;
    this.instantValidator = instantValidator;
    this.responderCodeTranslator = responderCodeTranslator;
    this.unsignedAssertionsResponseHandler = unsignedAssertionsResponseHandler;
}
 
Example 4
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void matchingResponseServiceShouldHandleSuccessMatchSaml() throws Exception {
    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    Status successStatus = aStatus().
        withStatusCode(aStatusCode().withValue(StatusCode.SUCCESS).build())
        .build();
    Response response = signResponse(createNoAttributeResponseBuilder(successStatus), testRpSigningCredential);

    TranslatedResponseBody result = matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );

    assertThat(result).isEqualTo(new TranslatedMatchingResponseBody(
        SUCCESS_MATCH,
        "some-pid",
        LevelOfAssurance.LEVEL_2,
        null
    ));
}
 
Example 5
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void matchingResponseServiceShouldHandleAccountCreationSaml() throws Exception {
    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    Status successStatus = aStatus().
        withStatusCode(aStatusCode().withValue(StatusCode.SUCCESS).build())
        .build();
    Response response = signResponse(createAttributeResponseBuilder(successStatus), testRpSigningCredential);

    TranslatedMatchingResponseBody result = (TranslatedMatchingResponseBody) matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );

    assertThat(result.getScenario()).isEqualTo(ACCOUNT_CREATION);
    assertThat(result.getAttributes()).isNotNull();
}
 
Example 6
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldHandleNoMatchSaml() throws Exception {
    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    Status noMatchStatus = aStatus().
        withStatusCode(
            aStatusCode()
                .withValue(StatusCode.RESPONDER)
                .withSubStatusCode(aStatusCode().withValue(SamlStatusCode.NO_MATCH).build())
                .build())
        .build();
    Response response = signResponse(createNoAttributeResponseBuilder(noMatchStatus), testRpSigningCredential);

    TranslatedMatchingResponseBody result = (TranslatedMatchingResponseBody) matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );

    assertThat(result.getScenario()).isEqualTo(NO_MATCH);
}
 
Example 7
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldHandleRequestErrorSaml() throws Exception {
    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    Status noMatchStatus = aStatus().
        withStatusCode(
            aStatusCode()
                .withValue(StatusCode.RESPONDER)
                .withSubStatusCode(aStatusCode().withValue(StatusCode.REQUESTER).build())
                .build())
        .build();
    Response response = signResponse(createNoAttributeResponseBuilder(noMatchStatus), testRpSigningCredential);

    TranslatedMatchingResponseBody result = (TranslatedMatchingResponseBody) matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );

    assertThat(result.getScenario()).isEqualTo(REQUEST_ERROR);
}
 
Example 8
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldHandleNoAuthnContextSaml() throws Exception {
    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    Status noMatchStatus = aStatus().
        withStatusCode(
            aStatusCode()
                .withValue(StatusCode.RESPONDER)
                .withSubStatusCode(aStatusCode().withValue(StatusCode.NO_AUTHN_CONTEXT).build())
                .build())
        .build();
    Response response = signResponse(createNoAttributeResponseBuilder(noMatchStatus), testRpSigningCredential);

    TranslatedMatchingResponseBody result = (TranslatedMatchingResponseBody) matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );

    assertThat(result.getScenario()).isEqualTo(CANCELLATION);
}
 
Example 9
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldHandleAuthenticationFailedSaml() throws Exception {
    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    Status noMatchStatus = aStatus().
        withStatusCode(
            aStatusCode()
                .withValue(StatusCode.RESPONDER)
                .withSubStatusCode(aStatusCode().withValue(StatusCode.AUTHN_FAILED).build())
                .build())
        .build();
    Response response = signResponse(createNoAttributeResponseBuilder(noMatchStatus), testRpSigningCredential);

    TranslatedMatchingResponseBody result = (TranslatedMatchingResponseBody) matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );

    assertThat(result.getScenario()).isEqualTo(AUTHENTICATION_FAILED);
}
 
Example 10
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldFailWhenUnrecognizedStatus() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Unknown SAML status: UNKNOWN");

    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    Status noMatchStatus = aStatus().
        withStatusCode(
            aStatusCode()
                .withValue("UNKNOWN")
                .build())
        .build();
    Response response = signResponse(createNoAttributeResponseBuilder(noMatchStatus), testRpSigningCredential);

    matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );
}
 
Example 11
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldFailWhenUnrecognizedSubStatus() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Unknown SAML sub-status: UNKNOWN");

    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    Status noMatchStatus = aStatus().
        withStatusCode(
            aStatusCode()
                .withValue(StatusCode.RESPONDER)
                .withSubStatusCode(aStatusCode().withValue("UNKNOWN").build())
                .build())
        .build();
    Response response = signResponse(createNoAttributeResponseBuilder(noMatchStatus), testRpSigningCredential);

    matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );
}
 
Example 12
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldFailValidationWhenHubMetadataDoesNotContainCorrectCertificate() throws Exception {
    expectedException.expect(SamlTransformationErrorException.class);
    expectedException.expectMessage("SAML Validation Specification: Signature was not valid.");

    Status successStatus = aStatus().
        withStatusCode(aStatusCode().withValue(StatusCode.SUCCESS).build())
        .build();
    Response response = signResponse(createNoAttributeResponseBuilder(successStatus), testRpSigningCredential);
    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_PUBLIC_CERT);

    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );
}
 
Example 13
Source Project: cxf-fediz   Source File: SAML2PResponseComponentBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Response createSAMLResponse(
    String inResponseTo,
    Issuer issuer,
    Status status
) {
    if (responseBuilder == null) {
        responseBuilder = (SAMLObjectBuilder<Response>)
            builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
    }
    Response response = responseBuilder.buildObject();

    response.setID(UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(inResponseTo);
    response.setIssuer(issuer);
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);

    return response;
}
 
Example 14
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldFailWhenIssueInstantIsTooOld() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Response IssueInstant is too far in the past ");

    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    ResponseBuilder responseBuilder = aResponse().withIssueInstant(DateTime.now().minusMinutes(10));
    Response response = signResponse(responseBuilder, testRpSigningCredential);

    matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );
}
 
Example 15
Source Project: verify-service-provider   Source File: ResponseServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldFailWhenIssueInstantIsInTheFuture() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Response IssueInstant is in the future ");

    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    ResponseBuilder responseBuilder = aResponse().withIssueInstant(DateTime.now().plusMinutes(1));
    Response response = signResponse(responseBuilder, testRpSigningCredential);

    matchingResponseService.convertTranslatedResponseBody(
        responseToBase64StringTransformer.apply(response),
        response.getInResponseTo(),
        LevelOfAssurance.LEVEL_2,
        VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );
}
 
Example 16
Source Project: saml-client   Source File: SamlClient.java    License: MIT License 6 votes vote down vote up
/**
 * Decodes and validates an SAML response returned by an identity provider.
 *
 * @param encodedResponse the encoded response returned by the identity provider.
 * @param method The HTTP method used by the request
 *
 * @return An {@link SamlResponse} object containing information decoded from the SAML response.
 * @throws SamlException if the signature is invalid, or if any other error occurs.
 */
public SamlResponse decodeAndValidateSamlResponse(String encodedResponse, String method)
    throws SamlException {
  //Decode and parse the response
  Response response = (Response) parseResponse(encodedResponse, method);

  // Decode and add the assertion
  try {
    decodeEncryptedAssertion(response);
  } catch (DecryptionException e) {
    throw new SamlException("Cannot decrypt the assertion", e);
  }
  //Validate  the response (Assertion / Signature / Schema)
  ValidatorUtils.validate(response, responseIssuer, credentials, this.now, notBeforeSkew);

  Assertion assertion = response.getAssertions().get(0);
  return new SamlResponse(assertion);
}
 
Example 17
Source Project: saml-client   Source File: ValidatorUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Validate assertion.
 *
 * @param response       the response
 * @param responseIssuer the response issuer
 * @param now            the current date time (for unit test only)
 * @param notBeforeSkew  the notBeforeSkew
 * @throws SamlException the saml exception
 */
private static void validateAssertion(
    Response response, String responseIssuer, DateTime now, long notBeforeSkew)
    throws SamlException {
  if (response.getAssertions().size() != 1) {
    throw new SamlException("The response doesn't contain exactly 1 assertion");
  }

  Assertion assertion = response.getAssertions().get(0);
  if (!assertion.getIssuer().getValue().equals(responseIssuer)) {
    throw new SamlException("The assertion issuer didn't match the expected value");
  }

  if (assertion.getSubject().getNameID() == null) {
    throw new SamlException(
        "The NameID value is missing from the SAML response; this is likely an IDP configuration issue");
  }

  enforceConditions(assertion.getConditions(), now, notBeforeSkew);
}
 
Example 18
Source Project: cxf-fediz   Source File: SAML2PResponseComponentBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Response createSAMLResponse(
    String inResponseTo,
    String issuer,
    Status status
) {
    if (responseBuilder == null) {
        responseBuilder = (SAMLObjectBuilder<Response>)
            builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
    }
    Response response = responseBuilder.buildObject();

    response.setID("_" + UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(inResponseTo);
    response.setIssuer(createIssuer(issuer));
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);

    return response;
}
 
Example 19
Source Project: cxf   Source File: SAML2PResponseComponentBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static Response createSAMLResponse(
    String inResponseTo,
    String issuer,
    Status status
) {
    if (responseBuilder == null) {
        responseBuilder = (SAMLObjectBuilder<Response>)
            builderFactory.getBuilder(Response.DEFAULT_ELEMENT_NAME);
    }
    Response response = responseBuilder.buildObject();

    response.setID(UUID.randomUUID().toString());
    response.setIssueInstant(new DateTime());
    response.setInResponseTo(inResponseTo);
    response.setIssuer(createIssuer(issuer));
    response.setStatus(status);
    response.setVersion(SAMLVersion.VERSION_20);

    return response;
}
 
Example 20
Source Project: cxf   Source File: SAMLSSOResponseValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testCreateAndValidateResponse() throws Exception {
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress("http://apache.org");
    subjectConfirmationData.setInResponseTo("12345");
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient("http://recipient.apache.org");

    Response response = createResponse(subjectConfirmationData);

    // Validate the Response
    SAMLSSOResponseValidator validator = new SAMLSSOResponseValidator();
    validator.setEnforceAssertionsSigned(false);
    validator.setIssuerIDP("http://cxf.apache.org/issuer");
    validator.setAssertionConsumerURL("http://recipient.apache.org");
    validator.setClientAddress("http://apache.org");
    validator.setRequestId("12345");
    validator.setSpIdentifier("http://service.apache.org");

    SSOValidatorResponse validateSamlResponse = validator.validateSamlResponse(response, false);
    assertEquals(response.getID(), validateSamlResponse.getResponseId());
    assertNotNull(validateSamlResponse.getAssertionElement());
    assertNotNull(validateSamlResponse.getCreated());
    assertNotNull(validateSamlResponse.getSessionNotOnOrAfter());
}
 
Example 21
Source Project: cxf-fediz   Source File: SamlResponseCreator.java    License: Apache License 2.0 6 votes vote down vote up
protected Element createResponse(Idp idp, String requestID, Assertion assertion) throws Exception {
    Document doc = DOMUtils.newDocument();

    Status status =
        SAML2PResponseComponentBuilder.createStatus(
            "urn:oasis:names:tc:SAML:2.0:status:Success", null
        );
    String issuer = isUseRealmForIssuer() ? idp.getRealm() : idp.getIdpUrl().toString();
    Response response =
        SAML2PResponseComponentBuilder.createSAMLResponse(requestID, issuer, status);

    response.getAssertions().add(assertion);

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

    return policyElement;
}
 
Example 22
Source Project: cxf   Source File: SAMLSSOResponseValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testInvalidRequestId() throws Exception {
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress("http://apache.org");
    subjectConfirmationData.setInResponseTo("12345-bad");
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient("http://recipient.apache.org");

    Response response = createResponse(subjectConfirmationData);

    // Validate the Response
    SAMLSSOResponseValidator validator = new SAMLSSOResponseValidator();
    validator.setEnforceAssertionsSigned(false);
    validator.setIssuerIDP("http://cxf.apache.org/issuer");
    validator.setAssertionConsumerURL("http://recipient.apache.org");
    validator.setClientAddress("http://apache.org");
    validator.setRequestId("12345");
    validator.setSpIdentifier("http://service.apache.org");
    try {
        validator.validateSamlResponse(response, false);
        fail("Expected failure on bad response");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 23
Source Project: cxf-fediz   Source File: SamlSso.java    License: Apache License 2.0 6 votes vote down vote up
@GET
public javax.ws.rs.core.Response login(@QueryParam("SAMLRequest") String samlRequest,
        @QueryParam("RelayState") String relayState, @QueryParam("binding") String binding) throws Exception {

    AuthnRequest request = extractRequest(samlRequest);

    String racs = request.getAssertionConsumerServiceURL();
    String requestIssuer = request.getIssuer().getValue();

    // Create the response
    Element response = createResponse(request.getID(), racs, requestIssuer);
    boolean redirect = "REDIRECT".equals(binding);
    String responseStr = encodeResponse(response, redirect);

    if (redirect) {
        return redirectResponse(relayState, racs, responseStr);
    } else {
        return postBindingResponse(relayState, racs, responseStr);
    }
}
 
Example 24
Source Project: cxf   Source File: SAMLSSOResponseValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testResponseInvalidIssuer() throws Exception {
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress("http://apache.org");
    subjectConfirmationData.setInResponseTo("12345");
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient("http://recipient.apache.org");

    Response response = createResponse(subjectConfirmationData);
    response.setIssuer(SAML2PResponseComponentBuilder.createIssuer("xyz"));

    // Validate the Response
    SAMLSSOResponseValidator validator = new SAMLSSOResponseValidator();
    validator.setEnforceAssertionsSigned(false);
    validator.setIssuerIDP("http://cxf.apache.org/issuer");
    validator.setAssertionConsumerURL("http://recipient.apache.org");
    validator.setClientAddress("http://apache.org");
    validator.setRequestId("12345");
    validator.setSpIdentifier("http://service.apache.org");
    try {
        validator.validateSamlResponse(response, false);
        fail("Expected failure on bad response");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 25
Source Project: cxf   Source File: SAMLSSOResponseValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testMissingAuthnStatement() throws Exception {
    SubjectConfirmationDataBean subjectConfirmationData = new SubjectConfirmationDataBean();
    subjectConfirmationData.setAddress("http://apache.org");
    subjectConfirmationData.setInResponseTo("12345");
    subjectConfirmationData.setNotAfter(new DateTime().plusMinutes(5));
    subjectConfirmationData.setRecipient("http://recipient.apache.org");

    Response response = createResponse(subjectConfirmationData);
    response.getAssertions().get(0).getAuthnStatements().clear();

    // Validate the Response
    SAMLSSOResponseValidator validator = new SAMLSSOResponseValidator();
    validator.setEnforceAssertionsSigned(false);
    validator.setIssuerIDP("http://cxf.apache.org/issuer");
    validator.setAssertionConsumerURL("http://recipient.apache.org");
    validator.setClientAddress("http://apache.org");
    validator.setRequestId("12345");
    validator.setSpIdentifier("http://service.apache.org");
    try {
        validator.validateSamlResponse(response, false);
        fail("Expected failure on bad response");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 26
Source Project: cxf   Source File: SAMLSSOResponseValidatorTest.java    License: Apache License 2.0 6 votes vote down vote up
@org.junit.Test
public void testNoSubjectConfirmationData() throws Exception {
    Response response = createResponse(null);

    // Validate the Response
    SAMLSSOResponseValidator validator = new SAMLSSOResponseValidator();
    validator.setEnforceAssertionsSigned(false);
    validator.setIssuerIDP("http://cxf.apache.org/issuer");
    validator.setAssertionConsumerURL("http://recipient.apache.org");
    validator.setClientAddress("http://apache.org");
    validator.setRequestId("12345");
    validator.setSpIdentifier("http://service.apache.org");
    try {
        validator.validateSamlResponse(response, false);
        fail("Expected failure on bad response");
    } catch (WSSecurityException ex) {
        // expected
    }
}
 
Example 27
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 28
@Override
public final QName getSamlObjectQName(final Class objectType) throws RuntimeException {
    try {
        final Field f = objectType.getField(DEFAULT_ELEMENT_LOCAL_NAME_FIELD);
        final String name = f.get(null).toString();

        if (objectType.equals(Response.class) || objectType.equals(Status.class)
                || objectType.equals(StatusCode.class)) {
            return new QName(SAMLConstants.SAML20P_NS, name, "samlp");
        }
        return new QName(SAMLConstants.SAML20_NS, name, XMLConstants.DEFAULT_NS_PREFIX);
    } catch (final Exception e){
        throw new IllegalStateException("Cannot access field " + objectType.getName() + '.' + DEFAULT_ELEMENT_LOCAL_NAME_FIELD);
    }
}
 
Example 29
Source Project: centraldogma   Source File: SamlAuthSsoHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private String findLoginNameFromSubjects(Response response) {
    if (Strings.isNullOrEmpty(subjectLoginNameIdFormat)) {
        return null;
    }
    return response.getAssertions()
                   .stream()
                   .map(s -> s.getSubject().getNameID())
                   .filter(nameId -> nameId.getFormat().equals(subjectLoginNameIdFormat))
                   .map(NameIDType::getValue)
                   .findFirst()
                   .orElse(null);
}
 
Example 30
Source Project: centraldogma   Source File: SamlAuthSsoHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public HttpResponse loginFailed(ServiceRequestContext ctx, AggregatedHttpRequest req,
                                @Nullable MessageContext<Response> message, Throwable cause) {
    final HttpStatus status =
            cause instanceof InvalidSamlRequestException ? HttpStatus.BAD_REQUEST
                                                         : HttpStatus.INTERNAL_SERVER_ERROR;
    return HttpApiUtil.newResponse(ctx, status, cause);
}