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

The following examples show how to use org.opensaml.saml.saml2.core.Assertion. 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
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 2
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 3
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 4
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 5
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 6
@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 7
@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 8
@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 9
@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
@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 11
Source Project: cxf   Source File: CustomSaml2Validator.java    License: 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 12
@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 13
Source Project: verify-service-provider   Source File: AssertionValidatorTest.java    License: 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 14
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 15
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 16
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 17
/**
 * Construct SAML response.
 * <a href="http://bit.ly/1uI8Ggu">See this reference for more info.</a>
 * @return the SAML response
 */
private String constructSamlResponse() {
    final DateTime currentDateTime = DateTime.parse(new ISOStandardDateFormat().getCurrentDateAndTime());
    final DateTime notBeforeIssueInstant = DateTime.parse("2003-04-17T00:46:02Z");

    final RegisteredService svc = this.servicesManager.findServiceBy(this);
    final String userId = svc.getUsernameAttributeProvider().resolveUsername(getPrincipal(), this);

    final org.opensaml.saml.saml2.core.Response response = BUILDER.newResponse(
            BUILDER.generateSecureRandomId(),
            currentDateTime,
            getId(), this);
    response.setStatus(BUILDER.newStatus(StatusCode.SUCCESS, null));

    final AuthnStatement authnStatement = BUILDER.newAuthnStatement(
            AuthnContext.PASSWORD_AUTHN_CTX, currentDateTime);
    final Assertion assertion = BUILDER.newAssertion(authnStatement,
            "https://www.opensaml.org/IDP",
            notBeforeIssueInstant, BUILDER.generateSecureRandomId());

    final Conditions conditions = BUILDER.newConditions(notBeforeIssueInstant,
            currentDateTime, getId());
    assertion.setConditions(conditions);

    final Subject subject = BUILDER.newSubject(NameID.EMAIL, userId,
            getId(), currentDateTime, this.requestId);
    assertion.setSubject(subject);

    response.getAssertions().add(assertion);

    final StringWriter writer = new StringWriter();
    BUILDER.marshalSamlXmlObject(response, writer);

    final String result = writer.toString();
    logger.debug("Generated Google SAML response: {}", result);
    return result;
}
 
Example 18
/**
 * Create a new SAML1 response object.
 *
 * @param authnStatement the authn statement
 * @param issuer the issuer
 * @param issuedAt the issued at
 * @param id the id
 * @return the assertion
 */
public Assertion newAssertion(final AuthnStatement authnStatement, final String issuer,
                              final DateTime issuedAt, final String id) {
    final Assertion assertion = newSamlObject(Assertion.class);
    assertion.setID(id);
    assertion.setIssueInstant(issuedAt);
    assertion.setIssuer(newIssuer(issuer));
    assertion.getAuthnStatements().add(authnStatement);
    return assertion;
}
 
Example 19
@Override
public TranslatedNonMatchingResponseBody translateSuccessResponse(List<Assertion> assertions, String expectedInResponseTo, LevelOfAssurance expectedLevelOfAssurance, String entityId) {
    if (assertions.size() != 1) {
        throw new SamlResponseValidationException("Exactly one country assertion is expected.");
    }

    final Assertion countryAssertion = assertions.get(ONLY_ONE_PRESENT);
    validateCountryAssertion(countryAssertion, expectedInResponseTo);

    final LevelOfAssurance levelOfAssurance = extractLevelOfAssuranceFrom(countryAssertion);
    levelOfAssuranceValidator.validate(levelOfAssurance, expectedLevelOfAssurance);

    return translateAssertion(countryAssertion, levelOfAssurance, getAuthnContext(extractLevelOfAssuranceUriFrom(countryAssertion)));
}
 
Example 20
private void validateCountryAssertion(Assertion assertion, String expectedInResponseTo) {
    String issuerEntityId = assertion.getIssuer().getValue();
    validateSignature(assertion, issuerEntityId);
    instantValidator.validate(assertion.getIssueInstant(), "Country Assertion IssueInstant");
    subjectValidator.validate(assertion.getSubject(), expectedInResponseTo);
    conditionsValidator.validate(assertion.getConditions(), acceptableHubConnectorEntityIds.toArray(new String[0]));
}
 
Example 21
public LevelOfAssurance extractLevelOfAssuranceFrom(Assertion countryAssertion) {
    String levelOfAssuranceString = extractLevelOfAssuranceUriFrom(countryAssertion);

    try {
        return LevelOfAssurance.fromSamlValue(new AuthnContextFactory().mapFromEidasToLoA(levelOfAssuranceString).getUri());
    } catch (Exception ex) {
        throw new SamlResponseValidationException(String.format("Level of assurance '%s' is not supported.", levelOfAssuranceString));
    }
}
 
Example 22
Source Project: verify-service-provider   Source File: EidasAssertionTranslator.java    License: MIT License 5 votes vote down vote up
@Override
protected void validateSignature(Assertion assertion, String issuerEntityId) {
    metadataResolverRepository.getSignatureTrustEngine(issuerEntityId)
            .map(signatureValidatorFactory::getSignatureValidator)
            .orElseThrow(() -> new SamlResponseValidationException("Unable to find metadata resolver for entity Id " + issuerEntityId))
            .validate(singletonList(assertion), IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
}
 
Example 23
Source Project: carbon-apimgt   Source File: SAMLGroupIDExtractorImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the organization list from the SAML2 Assertion
 *
 * @param assertions SAML2 assertions returned in SAML response
 * @return Organization list from the assertion
 */
private String getOrganizationFromSamlAssertion(List<Assertion> assertions) {
    List<String> attributeValueArray = new ArrayList<>();
    String organizationAttributeName = getOrganizationClaim();

    for (Assertion assertion : assertions) {
        List<AttributeStatement> attributeStatementList = assertion.getAttributeStatements();
        if (attributeStatementList != null) {
            for (AttributeStatement statement : attributeStatementList) {
                List<Attribute> attributesList = statement.getAttributes();
                for (Attribute attribute : attributesList) {
                    String attributeName = attribute.getName();
                    if (organizationAttributeName.equals(attributeName)) {
                        List<XMLObject> attributeValues = attribute.getAttributeValues();
                        if (attributeValues != null) {
                            for (XMLObject attributeValue : attributeValues) {
                                attributeValueArray.add(getAttributeValue(attributeValue));
                            }
                        }
                    }
                }
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("Organization list found in assertion: " + attributeValueArray);
    }

    return String.join(",", attributeValueArray);
}
 
Example 24
String extractLevelOfAssuranceUriFrom(Assertion assertion) {
    AuthnStatement authnStatement = getAuthnStatementFrom(assertion);
    return ofNullable(authnStatement.getAuthnContext())
            .map(AuthnContext::getAuthnContextClassRef)
            .map(AuthnContextClassRef::getAuthnContextClassRef)
            .orElseThrow(() -> new SamlResponseValidationException("Expected a level of assurance."));
}
 
Example 25
public void validate(Assertion authnAssertion, Assertion mdsAssertion, String requestId, LevelOfAssurance expectedLevelOfAssurance, LevelOfAssurance levelOfAssurance) {

        validateIdpAssertion(authnAssertion, requestId, IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
        validateIdpAssertion(mdsAssertion, requestId, IDPSSODescriptor.DEFAULT_ELEMENT_NAME);

        levelOfAssuranceValidator.validate(levelOfAssurance, expectedLevelOfAssurance);

        if (!mdsAssertion.getIssuer().getValue().equals(authnAssertion.getIssuer().getValue())) {
            throw new SamlResponseValidationException(MISMATCHED_ISSUERS);
        }

        if (!mdsAssertion.getSubject().getNameID().getValue().equals(authnAssertion.getSubject().getNameID().getValue())) {
            throw new SamlResponseValidationException(MISMATCHED_PIDS);
        }
    }
 
Example 26
private Assertion getMatchingDatasetAssertion(Collection<Assertion> assertions) {
    Map<AssertionType, List<Assertion>> assertionMap = assertions.stream()
            .collect(Collectors.groupingBy(assertionClassifierService::classifyAssertion));

    List<Assertion> mdsAssertions = assertionMap.get(AssertionType.MDS_ASSERTION);
    if (mdsAssertions == null || mdsAssertions.size() != 1) {
        throw new SamlResponseValidationException("Exactly one matching dataset assertion is expected.");
    }

    return mdsAssertions.get(0);
}
 
Example 27
public LevelOfAssurance extractLevelOfAssuranceFrom(Assertion authnAssertion) {
    String levelOfAssuranceUri = extractLevelOfAssuranceUriFrom(authnAssertion);

    try {
        return LevelOfAssurance.fromSamlValue(levelOfAssuranceUri);
    } catch (Exception ex) {
        throw new SamlResponseValidationException(String.format("Level of assurance '%s' is not supported.", levelOfAssuranceUri));
    }
}
 
Example 28
@Override
public TranslatedResponseBody translateSuccessResponse(
        List<Assertion> assertions,
        String expectedInResponseTo,
        LevelOfAssurance expectedLevelOfAssurance,
        String entityId
) {
    //  1. check saml has assertions
    checkSamlhasAssertions(assertions);
    //  2. validate assertions
    Assertion assertion = assertions.get(0);
    assertionValidator.validate(assertion, expectedInResponseTo, entityId);
    assertionsSignatureValidator.validate(assertions, IDPSSODescriptor.DEFAULT_ELEMENT_NAME);
    //  3. validate levelOfAssurance
    AuthnStatement authnStatement = assertion.getAuthnStatements().get(0);
    LevelOfAssurance levelOfAssurance = extractLevelOfAssurance(authnStatement);
    levelOfAssuranceValidator.validate(levelOfAssurance, expectedLevelOfAssurance);
    //  4. translateAssertions
    String nameID = assertion.getSubject().getNameID().getValue();
    List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
    if (isUserAccountCreation(attributeStatements)) {
        return new TranslatedMatchingResponseBody(
            ACCOUNT_CREATION,
            nameID,
            levelOfAssurance,
            AttributeTranslator.translateAttributes(attributeStatements.get(0))
        );

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

}
 
Example 29
Source Project: verify-service-provider   Source File: ResponseService.java    License: MIT License 5 votes vote down vote up
public TranslatedResponseBody convertTranslatedResponseBody(
    String decodedSamlResponse,
    String expectedInResponseTo,
    LevelOfAssurance expectedLevelOfAssurance,
    String entityId
) {
    Response response = samlObjectTransformer.apply(decodedSamlResponse);
    ValidatedResponse validatedResponse = responseSignatureValidator.validate(response, SPSSODescriptor.DEFAULT_ELEMENT_NAME);

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

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

    StatusCode statusCode = validatedResponse.getStatus().getStatusCode();

    switch (statusCode.getValue()) {
        case StatusCode.RESPONDER:
            return responderCodeTranslator.translateResponderCode(statusCode);
        case StatusCode.SUCCESS:
            List<Assertion> assertions = assertionDecrypter.decryptAssertions(validatedResponse);
            if (assertionsContainEidasUnsignedAssertionsResponse(assertions)) {
                if (unsignedAssertionsResponseHandler == null) { throw new MissingUnsignedAssertionsHandlerException(); }

                ValidatedResponse validatedCountryResponse = unsignedAssertionsResponseHandler.getValidatedResponse(assertions, expectedInResponseTo);
                assertions = unsignedAssertionsResponseHandler.decryptAssertion(validatedCountryResponse, assertions.get(ONLY_ONE_PRESENT));
            }
            return assertionTranslator.translateSuccessResponse(assertions, expectedInResponseTo, expectedLevelOfAssurance, entityId);
        default:
            throw new SamlResponseValidationException(String.format("Unknown SAML status: %s", statusCode.getValue()));
    }
}
 
Example 30
Source Project: verify-service-provider   Source File: ResponseService.java    License: 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
                    )
            );
}