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

The following examples show how to use org.opensaml.saml.saml2.core.Response. 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: SAML2PResponseComponentBuilder.java    From cxf-fediz with 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 #2
Source File: SAMLSSOResponseValidatorTest.java    From cxf with 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 #3
Source File: SAML2PResponseComponentBuilder.java    From cxf with 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 #4
Source File: SamlResponseCreator.java    From cxf-fediz with 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 #5
Source File: ResponseServiceTest.java    From verify-service-provider with 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 File: ResponseServiceTest.java    From verify-service-provider with 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 #7
Source File: SAMLSSOResponseValidatorTest.java    From cxf with 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 #8
Source File: ResponseService.java    From verify-service-provider with 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 #9
Source File: SamlAuthSsoHandler.java    From centraldogma with 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 #10
Source File: SAMLSSOResponseValidatorTest.java    From cxf with 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 #11
Source File: SAMLSSOResponseValidatorTest.java    From cxf with 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 #12
Source File: AbstractSaml20ObjectBuilder.java    From springboot-shiro-cas-mybatis with MIT License 6 votes vote down vote up
/**
 * 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 #13
Source File: SamlSso.java    From cxf-fediz with 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 #14
Source File: ResponseServiceTest.java    From verify-service-provider with 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 #15
Source File: SAMLSSOResponseValidatorTest.java    From cxf with 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 #16
Source File: ValidatorUtils.java    From saml-client with 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 #17
Source File: SamlClient.java    From saml-client with 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 #18
Source File: ResponseServiceTest.java    From verify-service-provider with 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 #19
Source File: ResponseServiceTest.java    From verify-service-provider with 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 #20
Source File: SAML2PResponseComponentBuilder.java    From cxf-fediz with 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 #21
Source File: ResponseServiceTest.java    From verify-service-provider with 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 #22
Source File: ResponseServiceTest.java    From verify-service-provider with 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 #23
Source File: ResponseServiceTest.java    From verify-service-provider with 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 #24
Source File: ResponseServiceTest.java    From verify-service-provider with 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 #25
Source File: ResponseServiceTest.java    From verify-service-provider with 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 #26
Source File: ResponseServiceTest.java    From verify-service-provider with 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 #27
Source File: SAML2PResponseComponentBuilder.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static Response createSAMLResponse(final String inResponseTo, final String issuer, final Status status) {
    if (responseBuilder == null) {
        responseBuilder = new ResponseBuilder();
    }
    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 #28
Source File: SAML2ReaderWriter.java    From syncope with Apache License 2.0 5 votes vote down vote up
public SSOValidatorResponse validate(
        final Response samlResponse,
        final SAML2IdPEntity idp,
        final String assertionConsumerURL,
        final String requestId,
        final String spEntityID)
        throws WSSecurityException {

    // validate the SAML response and, if needed, decrypt the provided assertion(s)
    Merlin crypto = new Merlin();
    crypto.setKeyStore(loader.getKeyStore());
    crypto.setTrustStore(idp.getTrustStore());

    SAMLProtocolResponseValidator protocolValidator = new SAMLProtocolResponseValidator();
    protocolValidator.setKeyInfoMustBeAvailable(true);
    protocolValidator.validateSamlResponse(samlResponse, crypto, callbackHandler);

    SAMLSSOResponseValidator ssoResponseValidator = new SAMLSSOResponseValidator();
    ssoResponseValidator.setAssertionConsumerURL(assertionConsumerURL);
    ssoResponseValidator.setIssuerIDP(idp.getId());
    ssoResponseValidator.setRequestId(requestId);
    ssoResponseValidator.setSpIdentifier(spEntityID);
    SSOValidatorResponse validatorResponse =
            ssoResponseValidator.validateSamlResponse(samlResponse, idp.getBindingType() == SAML2BindingType.POST);

    if (LOG.isDebugEnabled()) {
        try {
            StringWriter writer = new StringWriter();
            write(writer, samlResponse, false);
            writer.close();

            LOG.debug("SAML response with decrypted assertions: {}", writer.toString());
        } catch (Exception e) {
            LOG.error("Could not log the SAML response with decrypted assertions", e);
        }
    }

    return validatorResponse;
}
 
Example #29
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 #30
Source File: SamlUtil.java    From armeria with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link NameID} which is matched to the specified {@code filter} from the {@link Response}.
 */
@Nullable
public static NameID getNameId(Response response, Predicate<NameID> filter) {
    return response.getAssertions().stream()
                   .map(s -> s.getSubject().getNameID())
                   .filter(filter)
                   .findFirst().orElse(null);
}