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

The following examples show how to use org.opensaml.saml.saml2.core.Assertion. 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: 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 #2
Source File: ClassifyingAssertionTranslatorTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldUseEidasUnsignedAssertionTranslatorIfAssertionsAreUnsigned() {
    Assertion assertion = mock(Assertion.class);
    List<Assertion> assertions = Arrays.asList(assertion);
    TranslatedNonMatchingResponseBody expectedResult = mock(TranslatedNonMatchingResponseBody.class);

    when(assertion.getSignature()).thenReturn(null);
    when(eidasAssertionService.isCountryAssertion(assertion)).thenReturn(true);
    when(eidasUnsignedAssertionTranslator.translateSuccessResponse(
            assertions,
            expectedInResponseTo,
            loa,
            entityId)
    ).thenReturn(expectedResult);

    TranslatedNonMatchingResponseBody actualResult =
            (TranslatedNonMatchingResponseBody) classifyingAssertionService
                    .translateSuccessResponse(
                            assertions,
                            expectedInResponseTo,
                            loa,
                            entityId
                    );

    assertThat(actualResult).isEqualTo(expectedResult);
}
 
Example #3
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 #4
Source File: VerifyAssertionTranslator.java    From verify-service-provider with MIT License 6 votes vote down vote up
public void validateIdpAssertion(Assertion assertion, String expectedInResponseTo, QName role) {

        if (assertion.getIssueInstant() == null) {
            throw new SamlResponseValidationException("Assertion IssueInstant is missing.");
        }

        if (assertion.getID() == null || assertion.getID().length() == 0) {
            throw new SamlResponseValidationException("Assertion Id is missing or blank.");
        }

        if (assertion.getIssuer() == null || assertion.getIssuer().getValue() == null || assertion.getIssuer().getValue().length() == 0) {
            throw new SamlResponseValidationException("Assertion with id " + assertion.getID() + " has missing or blank Issuer.");
        }

        if (assertion.getVersion() == null) {
            throw new SamlResponseValidationException("Assertion with id " + assertion.getID() + " has missing Version.");
        }

        if (!assertion.getVersion().equals(SAMLVersion.VERSION_20)) {
            throw new SamlResponseValidationException("Assertion with id " + assertion.getID() + " declared an illegal Version attribute value.");
        }

        assertionsSignatureValidator.validate(singletonList(assertion), role);
        subjectValidator.validate(assertion.getSubject(), expectedInResponseTo);
        attributeStatementValidator.validate(assertion);
    }
 
Example #5
Source File: UnsignedAssertionResponseHandlerTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void decryptAssertionShouldThrowIfWrongEncryptionAlgorithmUsed() throws Exception {
    handler = new UnsignedAssertionsResponseHandler(
            eidasValidatorFactory,
            stringToResponseTransformer,
            instantValidator,
            secretKeyDecryptorFactory,
            new EncryptionAlgorithmValidator(
                    ImmutableSet.of(
                            EncryptionConstants.ALGO_ID_BLOCKCIPHER_TRIPLEDES
                    ),
                    ImmutableSet.of(
                            EncryptionConstants.ALGO_ID_KEYTRANSPORT_RSAOAEP
                    )
            ),
            hubAssertionSignatureValidator
    );
    Assertion eidasSamlAssertion = anEidasSamlAssertion(singleKeyList);

    assertThrows(SamlFailedToDecryptException.class, () -> {
        handler.decryptAssertion(validatedResponse, eidasSamlAssertion);
    });
}
 
Example #6
Source File: ClassifyingAssertionTranslatorTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldUseEidasAssertionServiceIfAnyAssertionIsACountryAttributeQuery() {
    Assertion assertion1 = mock(Assertion.class);
    Assertion assertion2 = mock(Assertion.class);
    List<Assertion> assertions = Arrays.asList(assertion1, assertion2);
    TranslatedNonMatchingResponseBody expectedResult = mock(TranslatedNonMatchingResponseBody.class);

    when(assertion1.getSignature()).thenReturn(mock(SignatureImpl.class));
    when(eidasAssertionService.isCountryAssertion(assertion1)).thenReturn(false);
    when(eidasAssertionService.isCountryAssertion(assertion2)).thenReturn(true);
    when(eidasAssertionService.translateSuccessResponse(assertions, expectedInResponseTo, loa, entityId)).thenReturn(expectedResult);


    TranslatedNonMatchingResponseBody actualResult = (TranslatedNonMatchingResponseBody) classifyingAssertionService.translateSuccessResponse(assertions, expectedInResponseTo, loa, entityId);


    assertThat(actualResult).isEqualTo(expectedResult);
}
 
Example #7
Source File: BaseEidasAssertionTranslatorTestBase.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void expectedHashContainedInResponseBodyWhenUserIdFactoryIsCalledOnce() {
    String requestId = "requestId";
    String expectedHashed = "a5fbea969c3837a712cbe9e188804796828f369106478e623a436fa07e8fd298";
    TestTranslatedNonMatchingResponseBody expectedNonMatchingResponseBody = new TestTranslatedNonMatchingResponseBody(NonMatchingScenario.IDENTITY_VERIFIED, expectedHashed, LEVEL_2, null);

    Assertion eidasAssertion = anAssertionWithAuthnStatement(EIDAS_LOA_SUBSTANTIAL, requestId).buildUnencrypted();

    final String nameId = eidasAssertion.getSubject().getNameID().getValue();
    final String issuerId = eidasAssertion.getIssuer().getValue();

    when(userIdHashFactory.hashId(eq(issuerId), eq(nameId), eq(Optional.of(AuthnContext.LEVEL_2))))
            .thenReturn(expectedHashed);

    TranslatedNonMatchingResponseBody responseBody = assertionService.translateSuccessResponse(ImmutableList.of(eidasAssertion), "requestId", LEVEL_2, "default-entity-id");

    verify(userIdHashFactory, times(1)).hashId(issuerId,nameId, Optional.of(AuthnContext.LEVEL_2));
    assertThat(responseBody.toString()).contains(expectedNonMatchingResponseBody.getPid());
}
 
Example #8
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 #9
Source File: MatchingAssertionTranslatorTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void shouldThrowExceptionWithUnknownLevelOfAssurance() throws Exception {
    expectedException.expect(SamlResponseValidationException.class);
    expectedException.expectMessage("Level of assurance 'unknown' is not supported.");

    Assertion assertion = aSignedAssertion()
        .addAuthnStatement(anAuthnStatement()
            .withAuthnContext(anAuthnContext()
                .withAuthnContextClassRef(anAuthnContextClassRef()
                    .withAuthnContextClasRefValue("unknown")
                    .build())
                .build())
            .build())
        .buildUnencrypted();

    msaAssertionTranslator.translateSuccessResponse(ImmutableList.of(assertion), IN_RESPONSE_TO, LEVEL_2, VERIFY_SERVICE_PROVIDER_ENTITY_ID);
}
 
Example #10
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 #11
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
@Test
public void expectedHashContainedInResponseBodyWhenUserIdFactoryIsCalledOnce() {

    String requestId = "requestId";
    String expectedHashed = "a5fbea969c3837a712cbe9e188804796828f369106478e623a436fa07e8fd298";
    TestTranslatedNonMatchingResponseBody expectedNonMatchingResponseBody = new TestTranslatedNonMatchingResponseBody(NonMatchingScenario.IDENTITY_VERIFIED, expectedHashed, LEVEL_2, null);

    Assertion authnAssertion = anAuthnStatementAssertion(IdaAuthnContext.LEVEL_2_AUTHN_CTX, requestId).buildUnencrypted();
    Assertion mdsAssertion = aMatchingDatasetAssertionWithSignature(emptyList(), anIdpSignature(), requestId).buildUnencrypted();

    final String nameId = authnAssertion.getSubject().getNameID().getValue();
    final String issuerId = authnAssertion.getIssuer().getValue();

    when(userIdHashFactory.hashId(eq(issuerId), eq(nameId), eq(Optional.of(AuthnContext.LEVEL_2))))
            .thenReturn(expectedHashed);

    TranslatedNonMatchingResponseBody responseBody = verifyAssertionService.translateSuccessResponse(ImmutableList.of(authnAssertion, mdsAssertion), "requestId", LEVEL_2, "default-entity-id");

    verify(userIdHashFactory, times(1)).hashId(issuerId, nameId, Optional.of(AuthnContext.LEVEL_2));
    assertThat(responseBody.toString()).contains(expectedNonMatchingResponseBody.getPid());
}
 
Example #12
Source File: CustomSaml2Validator.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Override
public Credential validate(Credential credential, RequestData data) throws WSSecurityException {
    Credential validatedCredential = super.validate(credential, data);
    SamlAssertionWrapper assertion = validatedCredential.getSamlAssertion();

    if (!"sts".equals(assertion.getIssuerString())) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    Assertion saml2Assertion = assertion.getSaml2();
    if (saml2Assertion == null) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    List<AttributeStatement> attributeStatements = saml2Assertion.getAttributeStatements();
    if (attributeStatements == null || attributeStatements.isEmpty()) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    return validatedCredential;
}
 
Example #13
Source File: UnsignedAssertionsResponseHandler.java    From verify-service-provider with MIT License 6 votes vote down vote up
public ValidatedResponse getValidatedResponse(
        List<Assertion> hubResponseAssertion,
        String expectedInResponseTo
) {
    ValidatedAssertions validatedHubAssertion = hubAssertionsSignatureValidator.validate(hubResponseAssertion, SPSSODescriptor.DEFAULT_ELEMENT_NAME);
    ValidatedResponse validatedResponse = eidasValidatorFactory.getValidatedResponse(
            stringToResponseTransformer.apply(
                    getCountryResponseStringFromAssertion(validatedHubAssertion.getAssertions().get(ONLY_ONE_PRESENT))
            )
    );

    if (!expectedInResponseTo.equals(validatedResponse.getInResponseTo())) {
        throw new SamlResponseValidationException(
                String.format("Expected InResponseTo to be %s, but was %s", expectedInResponseTo, validatedResponse.getInResponseTo())
        );
    }

    instantValidator.validate(validatedResponse.getIssueInstant(), "Response IssueInstant");

    return validatedResponse;
}
 
Example #14
Source File: UnsignedAssertionsResponseHandler.java    From verify-service-provider with MIT License 6 votes vote down vote up
public List<Assertion> decryptAssertion(
        ValidatedResponse validatedResponse,
        Assertion hubResponseAssertion
) {
    Iterator<String> keysIterator = getEncryptedAssertionKeysFromAssertion(hubResponseAssertion).iterator();

    while (keysIterator.hasNext()) {
        String key = keysIterator.next();
        try {
            return getAssertionDecrypter(key).decryptAssertions(validatedResponse);
        } catch (Exception e) {
            if (keysIterator.hasNext()) {
                LOG.info("Failed to decrypt assertions with key, trying next available", e);
            } else {
                String message = String.format("Failed to decrypt assertions with any key for response ID %s", validatedResponse.getID());
                throw new SamlFailedToDecryptException(unableToDecrypt(message), e);
            }
        }
    }
    return new ArrayList<>();
}
 
Example #15
Source File: UnsignedAssertionsResponseHandler.java    From verify-service-provider with MIT License 6 votes vote down vote up
private List<String> getEncryptedAssertionKeysFromAssertion(Assertion hubResponseAssertion) {
    List<String> keys = new ArrayList<String>();
    hubResponseAssertion
            .getAttributeStatements()
            .get(0)
            .getAttributes()
            .stream()
            .filter(attribute -> attribute.getName().equals(IdaConstants.Eidas_Attributes.UnsignedAssertions.EncryptedSecretKeys.NAME))
            .forEach(attribute -> attribute
                    .getAttributeValues()
                    .stream()
                    .map(value -> (EncryptedAssertionKeys) value)
                    .forEach(value -> keys.add(value.getValue()))
            );
    return keys;
}
 
Example #16
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfMissingAssertionVersionWhenValidatingIdpAssertion() {
    Assertion assertion = aMatchingDatasetAssertionWithSignature(emptyList(), anIdpSignature(), "requestId").buildUnencrypted();
    assertion.setVersion(null);

    exception.expect(SamlResponseValidationException.class);
    exception.expectMessage("Assertion with id mds-assertion has missing Version.");
    verifyAssertionService.validateIdpAssertion(assertion, "not-used", IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
}
 
Example #17
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfIssuerValueIsBlankWhenValidatingIdpAssertion() {
    Assertion assertion = aMatchingDatasetAssertionWithSignature(emptyList(), anIdpSignature(), "requestId").buildUnencrypted();
    assertion.setIssuer(anIssuer().withIssuerId("").build());

    exception.expect(SamlResponseValidationException.class);
    exception.expectMessage("Assertion with id mds-assertion has missing or blank Issuer.");
    verifyAssertionService.validateIdpAssertion(assertion, "not-used", IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
}
 
Example #18
Source File: AssertionClassifierTests.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldClassifyAnAssertionBasedOnWhetherItContainsAuthnStatements() {
    Assertion mdsAssertion = aMatchingDatasetAssertion("requestId").buildUnencrypted();
    Assertion authnStatementAssertion = anAuthnStatementAssertion(IdaAuthnContext.LEVEL_2_AUTHN_CTX, "requestId").buildUnencrypted();

    AssertionClassifier assertionClassifier = new AssertionClassifier();

    assertThat(assertionClassifier.classifyAssertion(mdsAssertion)).isEqualTo(AssertionType.MDS_ASSERTION);
    assertThat(assertionClassifier.classifyAssertion(authnStatementAssertion)).isEqualTo(AssertionType.AUTHN_ASSERTION);
}
 
Example #19
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfIssuerValueMissingWhenValidatingIdpAssertion() {
    Assertion assertion = aMatchingDatasetAssertionWithSignature(emptyList(), anIdpSignature(), "requestId").buildUnencrypted();
    assertion.setIssuer(anIssuer().withIssuerId(null).build());

    exception.expect(SamlResponseValidationException.class);
    exception.expectMessage("Assertion with id mds-assertion has missing or blank Issuer.");
    verifyAssertionService.validateIdpAssertion(assertion, "not-used", IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
}
 
Example #20
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfIssuerMissingWhenValidatingIdpAssertion() {
    Assertion assertion = aMatchingDatasetAssertionWithSignature(emptyList(), anIdpSignature(), "requestId").buildUnencrypted();
    assertion.setIssuer(null);

    exception.expect(SamlResponseValidationException.class);
    exception.expectMessage("Assertion with id mds-assertion has missing or blank Issuer.");
    verifyAssertionService.validateIdpAssertion(assertion, "not-used", IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
}
 
Example #21
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfAssertionIdIsBlankWhenValidatingIdpAssertion() {
    Assertion assertion = aMatchingDatasetAssertionWithSignature(emptyList(), anIdpSignature(), "requestId").buildUnencrypted();
    assertion.setID("");

    exception.expect(SamlResponseValidationException.class);
    exception.expectMessage("Assertion Id is missing or blank.");
    verifyAssertionService.validateIdpAssertion(assertion, "not-used", IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
}
 
Example #22
Source File: ResponseServiceTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void nonMatchingResponseServiceShouldHandleUnsignedAssertions() throws Exception {
    EntityDescriptor entityDescriptor = createEntityDescriptorWithSigningCertificate(TEST_RP_PUBLIC_SIGNING_CERT);
    when(hubMetadataResolver.resolve(any())).thenReturn(ImmutableList.of(entityDescriptor));

    Response response = signResponse(createUnsignedAttributeResponseBuilder(), testRpSigningCredential);
    ValidatedResponse validatedResponse = new ValidatedResponse(response);
    List<Assertion> decryptedAssertion = asList(mock(Assertion.class));
    TranslatedNonMatchingResponseBody expectedResponse = mock(TranslatedNonMatchingResponseBody.class);

    when(mockUnsignedAssertionsResponseHandler.getValidatedResponse(any(), eq(validatedResponse.getInResponseTo())))
            .thenReturn(validatedResponse);
    when(mockUnsignedAssertionsResponseHandler.decryptAssertion(eq(validatedResponse), any()))
            .thenReturn(decryptedAssertion);
    when(mockAssertionTranslator.translateSuccessResponse(eq(decryptedAssertion), eq(validatedResponse.getInResponseTo()), any(), any()))
            .thenReturn(expectedResponse);

    TranslatedNonMatchingResponseBody result = (TranslatedNonMatchingResponseBody) eidasNonMatchingResponseService.convertTranslatedResponseBody(
            responseToBase64StringTransformer.apply(response),
            response.getInResponseTo(),
            LevelOfAssurance.LEVEL_2,
            VERIFY_SERVICE_PROVIDER_ENTITY_ID
    );

    verify(mockUnsignedAssertionsResponseHandler).getValidatedResponse(any(), eq(response.getInResponseTo()));
    verify(mockUnsignedAssertionsResponseHandler).decryptAssertion(eq(validatedResponse), any());

    assertThat(result).isEqualTo(expectedResponse);
}
 
Example #23
Source File: ResponseService.java    From verify-service-provider with MIT License 5 votes vote down vote up
private boolean assertionsContainEidasUnsignedAssertionsResponse(List<Assertion> assertions) {
    if (assertions == null || assertions.size() != 1) { return false; }

    List<AttributeStatement> attributeStatements = assertions.get(ONLY_ONE_PRESENT).getAttributeStatements();
    if (attributeStatements.isEmpty() || attributeStatements.size() != 1) { return false; }

    return attributeStatements.get(ONLY_ONE_PRESENT).getAttributes()
            .stream()
            .anyMatch(
                    attribute -> attribute.getName().equals(
                            IdaConstants.Eidas_Attributes.UnsignedAssertions.EidasSamlResponse.NAME
                    )
            );
}
 
Example #24
Source File: Util.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 Assertion
 *
 * @param assertion SAML2 assertion
 * @return username
 */
public static String getUsernameFromAssertion(Assertion assertion, String usernameAttribute) {
    String username = null;
    if (!StringUtils.isEmpty(usernameAttribute)) {
        // There can be multiple AttributeStatements in Assertion
        List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
        if (attributeStatements != null) {
            for (AttributeStatement attributeStatement : attributeStatements) {
                // There can be multiple Attributes in an attributeStatement
                List<Attribute> attributes = attributeStatement.getAttributes();
                if (attributes != null) {
                    for (Attribute attribute : attributes) {
                        String attributeName = attribute.getDOM().getAttribute(SSOConstants.SAML_NAME_ATTRIBUTE);
                        if (attributeName.equals(usernameAttribute)) {
                            List<XMLObject> attributeValues = attribute.getAttributeValues();
                            // There can be multiple attribute values in an attribute, but get the first one
                            username = attributeValues.get(0).getDOM().getTextContent();
                            if (log.isDebugEnabled()) {
                                log.debug("Name of authenticated user from SAML response : " + username);
                            }
                        }
                    }
                }
            }
        }
    } else {
        Subject subject = assertion.getSubject();
        if (subject != null) {
            if (subject.getNameID() != null) {
                username = subject.getNameID().getValue();
                if (log.isDebugEnabled()) {
                    log.debug("Name of authenticated user from SAML response : " + username);
                }
            }
        }
    }
    return username;
}
 
Example #25
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionIfAssertionIdIsMissingWhenValidatingIdpAssertion() {
    Assertion assertion = aMatchingDatasetAssertionWithSignature(emptyList(), anIdpSignature(), "requestId").buildUnencrypted();
    assertion.setID(null);

    exception.expect(SamlResponseValidationException.class);
    exception.expectMessage("Assertion Id is missing or blank.");
    verifyAssertionService.validateIdpAssertion(assertion, "not-used", IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
}
 
Example #26
Source File: BaseEidasAssertionTranslatorTestBase.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldCorrectlyIdentifyCountryAssertions() {
    List<String> resolverEntityIds = asList("ID1", "ID2");
    when(metadataResolverRepository.getResolverEntityIds()).thenReturn(resolverEntityIds);

    Assertion countryAssertion = anAssertion().withIssuer(anIssuer().withIssuerId("ID1").build()).buildUnencrypted();
    Assertion idpAssertion = anAssertion().withIssuer(anIssuer().withIssuerId("ID3").build()).buildUnencrypted();

    assertThat(assertionService.isCountryAssertion(countryAssertion)).isTrue();
    assertThat(assertionService.isCountryAssertion(idpAssertion)).isFalse();
}
 
Example #27
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldThrowExceptionWithUnknownLevelOfAssurance() throws Exception {
    Assertion authnAssertion = anAuthnStatementAssertion("unknown", "requestId").buildUnencrypted();
    Assertion mdsAssertion = aMatchingDatasetAssertionWithSignature(emptyList(), anIdpSignature(), "requestId").buildUnencrypted();

    exception.expect(SamlResponseValidationException.class);
    exception.expectMessage("Level of assurance 'unknown' is not supported.");
    verifyAssertionService.translateSuccessResponse(ImmutableList.of(authnAssertion, mdsAssertion), "requestId", LEVEL_2, "default-entity-id");
}
 
Example #28
Source File: BaseEidasAssertionTranslatorTestBase.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldCorrectlyExtractLevelOfAssurance() {
    Assertion eidasAssertion = anAssertionWithAuthnStatement(EIDAS_LOA_SUBSTANTIAL, "requestId").buildUnencrypted();

    LevelOfAssurance loa = assertionService.extractLevelOfAssuranceFrom(eidasAssertion);

    assertThat(loa).isEqualTo(LEVEL_2);
}
 
Example #29
Source File: AssertionValidator.java    From verify-service-provider with MIT License 5 votes vote down vote up
public void validate(Assertion assertion, String expectedInResponseTo, String entityId) {
    instantValidator.validate(assertion.getIssueInstant(), "Assertion IssueInstant");
    subjectValidator.validate(assertion.getSubject(), expectedInResponseTo);
    conditionsValidator.validate(assertion.getConditions(), entityId);

    validateAuthnStatements(assertion.getAuthnStatements());

    instantValidator.validate(assertion.getAuthnStatements().get(0).getAuthnInstant(), "Assertion AuthnInstant");
}
 
Example #30
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
@Test
public void shouldNotThrowExceptionsWhenAssertionsAreValid() {
    Assertion authnAssertion = anAuthnStatementAssertion(IdaAuthnContext.LEVEL_2_AUTHN_CTX, "requestId").buildUnencrypted();
    Assertion mdsAssertion = aMatchingDatasetAssertionWithSignature(emptyList(), anIdpSignature(), "requestId").buildUnencrypted();

    verifyAssertionService.validate(authnAssertion, mdsAssertion, "requestId", LevelOfAssurance.LEVEL_1, LEVEL_2);

    verify(subjectValidator, times(2)).validate(any(), any());
    verify(hubSignatureValidator, times(2)).validate(any(), any());
    verify(levelOfAssuranceValidator, times(1)).validate(LEVEL_2, LEVEL_1);
}