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

The following examples show how to use org.opensaml.saml.saml2.core.AttributeStatement. 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: verify-service-provider   Source File: AttributeTranslatorTests.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldReturnAddressAttribute() {
    Attribute addressAttribute = new AddressAttributeBuilder_1_1()
        .addAddress(new AddressAttributeValueBuilder_1_1()
            .addLines(Arrays.asList("10 Whitechapel High St", "London"))
            .withPostcode("E1 8DX")
            .withFrom(DateTime.parse("2017-07-03"))
            .withTo(DateTime.parse("2017-07-30"))
            .build())
        .buildCurrentAddress();
    addressAttribute.setName("currentaddress");

    AttributeStatement attributeStatement = anAttributeStatement()
        .addAttribute(addressAttribute)
        .addAttribute(createVerifiedAttribute("currentaddress_verified", true))
        .build();

    Attributes result = AttributeTranslator.translateAttributes(attributeStatement);

    assertThat(result.getAddress()).isNotNull();
}
 
Example 2
Source Project: saml-client   Source File: SamlClient.java    License: MIT License 6 votes vote down vote up
/**
 * Gets attributes from the IDP Response
 *
 * @param response the response
 * @return the attributes
 */
public static Map<String, String> getAttributes(SamlResponse response) {
  HashMap<String, String> map = new HashMap<>();
  if (response == null) {
    return map;
  }
  List<AttributeStatement> attributeStatements = response.getAssertion().getAttributeStatements();
  if (attributeStatements == null) {
    return map;
  }

  for (AttributeStatement statement : attributeStatements) {
    for (Attribute attribute : statement.getAttributes()) {
      XMLObject xmlObject = attribute.getAttributeValues().get(0);
      if (xmlObject instanceof XSStringImpl) {
        map.put(attribute.getName(), ((XSStringImpl) xmlObject).getValue());
      } else {
        map.put(attribute.getName(), ((XSAnyImpl) xmlObject).getTextContent());
      }
    }
  }
  return map;
}
 
Example 3
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 4
Source Project: cxf   Source File: OnBehalfOfValidator.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();

    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");
    }

    Subject subject = saml2Assertion.getSubject();
    NameID nameID = subject.getNameID();
    String subjectName = nameID.getValue();
    if ("alice".equals(subjectName) || "bob".equals(subjectName)) {
        return validatedCredential;
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
 
Example 5
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 6
Source Project: verify-service-provider   Source File: AttributeTranslator.java    License: MIT License 5 votes vote down vote up
public static Attributes translateAttributes(AttributeStatement attributeStatement) {
    List<Attribute> statementAttributes = attributeStatement.getAttributes();

    VerifiableAttribute<String> verifiableFirstName = getVerifiableStringAttribute(statementAttributes, "firstname", "firstname_verified");
    VerifiableAttribute<String> verifiableMiddleName = getVerifiableStringAttribute(statementAttributes, "middlename", "middlename_verified");
    VerifiableAttribute<String> verifiableSurname = getVerifiableStringAttribute(statementAttributes, "surname", "surname_verified");
    VerifiableAttribute<LocalDate> verifiableDob = getVerifiableDateAttribute(statementAttributes, "dateofbirth", "dateofbirth_verified");
    VerifiableAttribute<Address> verifiableAddress = getVerifiableAddressAttribute(statementAttributes, "currentaddress", "currentaddress_verified");
    Optional<List<VerifiableAttribute<Address>>> addressHistory = getVerifiableAddressListAttribute(statementAttributes, "addresshistory");
    Optional<String> cycle3 = getStringAttributeValue(statementAttributes, "cycle_3");
    return new Attributes(verifiableFirstName, verifiableMiddleName, verifiableSurname, verifiableDob, verifiableAddress, addressHistory.orElse(null), cycle3.orElse(null));
}
 
Example 7
@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 8
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
                    )
            );
}
 
Example 9
Source Project: verify-service-provider   Source File: AssertionHelper.java    License: MIT License 5 votes vote down vote up
public static EncryptedAssertion anEidasEncryptedAssertion(String requestId,
                                                           String issuerId,
                                                           Signature assertionSignature,
                                                           AttributeStatement attributeStatement) {
    return anEidasEncryptedAssertion(
            requestId,
            issuerId,
            assertionSignature,
            attributeStatement,
            true,
            EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128
    );
}
 
Example 10
Source Project: verify-service-provider   Source File: AssertionHelper.java    License: MIT License 5 votes vote down vote up
public static EncryptedAssertion anEidasEncryptedAssertion(String requestId,
                                                           String issuerId,
                                                           Signature assertionSignature,
                                                           AttributeStatement attributeStatement,
                                                           boolean shouldSign,
                                                           String encryptionAlgorithm)
{
    AssertionBuilder assertionBuilder = anAssertion()
            .withSubject(
                    aSubject().withSubjectConfirmation(
                            aSubjectConfirmation().withSubjectConfirmationData(
                                    aSubjectConfirmationData()
                                            .withInResponseTo(requestId)
                                            .build())
                                    .build())
                            .build())
            .withIssuer(
                    anIssuer()
                            .withIssuerId(issuerId)
                            .build())
            .addAttributeStatement(attributeStatement)
            .addAuthnStatement(anEidasAuthnStatement().build())
            .withConditions(aConditionsForEidas());

    if (shouldSign) {
        assertionBuilder.withSignature(assertionSignature);
    } else {
        assertionBuilder.withoutSigning();
        assertionBuilder.withSignature(null);
    }

    return assertionBuilder.buildWithEncrypterCredential(
            new TestCredentialFactory(
                    TEST_RP_PUBLIC_ENCRYPTION_CERT,
                    TEST_RP_PRIVATE_ENCRYPTION_KEY
            ).getEncryptingCredential(),
            encryptionAlgorithm
    );
}
 
Example 11
Source Project: verify-service-provider   Source File: AssertionHelper.java    License: MIT License 5 votes vote down vote up
public static ResponseBuilder aValidEidasResponse(String requestId, String assertionIssuerId, AttributeStatement attributeStatement) {
    return ResponseBuilder.aResponse()
            .withId(requestId)
            .withInResponseTo(requestId)
            .withIssuer(anIssuer().withIssuerId(HUB_ENTITY_ID).build())
            .addEncryptedAssertion(anEidasEncryptedAssertion(requestId, assertionIssuerId, anEidasSignature(), attributeStatement))
            .withSigningCredential(
                    new TestCredentialFactory(
                            HUB_TEST_PUBLIC_SIGNING_CERT,
                            HUB_TEST_PRIVATE_SIGNING_KEY
                    ).getSigningCredential());
}
 
Example 12
Source Project: verify-service-provider   Source File: AssertionHelper.java    License: MIT License 5 votes vote down vote up
private static AttributeStatement anAttributeStatementContainingAnEidasUnsignedResponse(String countrySamlResponseValue, List<String> encryptedKeys) {
    CountrySamlResponse countrySamlAttributeValue = new CountrySamlResponseBuilder().buildObject();
    countrySamlAttributeValue.setValue(countrySamlResponseValue);

    Attribute countrySamlAttribute = (Attribute) XMLObjectSupport.buildXMLObject(Attribute.DEFAULT_ELEMENT_NAME);
    countrySamlAttribute.setName(IdaConstants.Eidas_Attributes.UnsignedAssertions.EidasSamlResponse.NAME);
    countrySamlAttribute.setFriendlyName(IdaConstants.Eidas_Attributes.UnsignedAssertions.EidasSamlResponse.FRIENDLY_NAME);
    countrySamlAttribute.setNameFormat(Attribute.URI_REFERENCE);

    countrySamlAttribute.getAttributeValues().add(countrySamlAttributeValue);

    List<EncryptedAssertionKeys> assertionKeysValues = new ArrayList<>();
    for (String key : encryptedKeys) {
        EncryptedAssertionKeys keysAttribtueValue = new EncryptedAssertionKeysBuilder().buildObject();
        keysAttribtueValue.setValue(key);
        assertionKeysValues.add(keysAttribtueValue);
    }

    Attribute keysAttribute = (Attribute) XMLObjectSupport.buildXMLObject(Attribute.DEFAULT_ELEMENT_NAME);
    keysAttribute.setName(IdaConstants.Eidas_Attributes.UnsignedAssertions.EncryptedSecretKeys.NAME);
    keysAttribute.setFriendlyName(IdaConstants.Eidas_Attributes.UnsignedAssertions.EncryptedSecretKeys.FRIENDLY_NAME);
    keysAttribute.setNameFormat(Attribute.URI_REFERENCE);

    keysAttribute.getAttributeValues().addAll(assertionKeysValues);

    return anAttributeStatement()
            .addAttribute(countrySamlAttribute)
            .addAttribute(keysAttribute)
            .build();
}
 
Example 13
Source Project: verify-service-provider   Source File: AttributeTranslatorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldReturnCorrectRequestedAttributes() {
    AttributeStatement attributeStatement = anAttributeStatement()
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("firstname")
            .withSimpleStringValue("Bob")
            .build())
        .addAttribute(createVerifiedAttribute("firstname_verified", false))
        .build();

    Attributes result = AttributeTranslator.translateAttributes(attributeStatement);

    assertThat(result.getFirstName()).isNotNull();
}
 
Example 14
Source Project: verify-service-provider   Source File: AttributeTranslatorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldReturnAllSimpleRequestedAttributes() {
    AttributeStatement attributeStatement = anAttributeStatement()
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("firstname")
            .withSimpleStringValue("Joe")
            .build())
        .addAttribute(createVerifiedAttribute("firstname_verified", true))
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("middlename")
            .withSimpleStringValue("Bob")
            .build())
        .addAttribute(createVerifiedAttribute("middlename_verified", false))
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("surname")
            .withSimpleStringValue("Bloggs")
            .build())
        .addAttribute(createVerifiedAttribute("surname_verified", true))
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("dateofbirth")
            .withSimpleStringValue("1977-07-21")
            .build())
        .addAttribute(createVerifiedAttribute("dateofbirth_verified", true))
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("cycle_3")
            .withSimpleStringValue("1")
            .build())
        .build();

    Attributes result = AttributeTranslator.translateAttributes(attributeStatement);

    assertThat(result.getFirstName()).isNotNull();
    assertThat(result.getMiddleName()).isNotNull();
    assertThat(result.getSurname()).isNotNull();
    assertThat(result.getDateOfBirth()).isNotNull();
    assertThat(result.getCycle3()).isNotEmpty();
}
 
Example 15
Source Project: verify-service-provider   Source File: AttributeTranslatorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldReturnAddressHistoryAttribute() {
    Attribute addressHistoryAttribute = new AddressAttributeBuilder_1_1()
        .addAddress(new AddressAttributeValueBuilder_1_1()
            .addLines(Arrays.asList("10 Whitechapel High St", "London"))
            .withPostcode("E1 8DX")
            .withFrom(DateTime.parse("2017-07-03"))
            .withTo(DateTime.parse("2017-07-30"))
            .withVerified(true)
            .build())
        .addAddress(new AddressAttributeValueBuilder_1_1()
            .addLines(Arrays.asList("42 Old Road", "London"))
            .withPostcode("W1 0AA")
            .withFrom(DateTime.parse("2015-01-01"))
            .withTo(DateTime.parse("2017-07-03"))
            .withVerified(true)
            .build())
        .buildPreviousAddress();
    addressHistoryAttribute.setName("addresshistory");

    AttributeStatement attributeStatement = anAttributeStatement()
        .addAttribute(addressHistoryAttribute)
        .build();

    Attributes result = AttributeTranslator.translateAttributes(attributeStatement);

    assertThat(result.getAddressHistory()).isNotNull();
    assertThat(result.getAddressHistory().size()).isEqualTo(2);
}
 
Example 16
Source Project: verify-service-provider   Source File: AttributeTranslatorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldIncludeEmptyAttributes() {
    AttributeStatement attributeStatement = anAttributeStatement()
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("firstname")
            .withSimpleStringValue("")
            .build())
        .addAttribute(createVerifiedAttribute("firstname_verified", true))
        .build();

    Attributes result = AttributeTranslator.translateAttributes(attributeStatement);

    assertThat(result.getFirstName().getValue()).isEmpty();
}
 
Example 17
Source Project: verify-service-provider   Source File: AttributeTranslatorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldNotReturnUnrequestedAttributes() {
    AttributeStatement attributeStatement = anAttributeStatement()
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("firstname")
            .withSimpleStringValue("Bob")
            .build())
        .addAttribute(createVerifiedAttribute("firstname_verified", true))
        .build();

    Attributes result = AttributeTranslator.translateAttributes(attributeStatement);

    assertThat(result.getSurname()).isNull();
}
 
Example 18
Source Project: verify-service-provider   Source File: AttributeTranslatorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldReturnCorrectValuesForAddressAttribute() {
    List<String> lines = Arrays.asList("10 Whitechapel High St", "London");
    String postCode = "E1 8DX";
    DateTime from = DateTime.parse("2017-07-03T12:00:00+01:00");
    DateTime to = DateTime.parse("2017-07-30T12:00:00+01:00");

    Attribute addressAttribute = new AddressAttributeBuilder_1_1()
        .addAddress(new AddressAttributeValueBuilder_1_1()
            .addLines(lines)
            .withPostcode(postCode)
            .withFrom(from)
            .withTo(to)
            .build())
        .buildCurrentAddress();
    addressAttribute.setName("currentaddress");

    AttributeStatement attributeStatement = anAttributeStatement()
        .addAttribute(addressAttribute)
        .addAttribute(createVerifiedAttribute("currentaddress_verified", true))
        .build();

    Attributes result = AttributeTranslator.translateAttributes(attributeStatement);

    assertThat(result.getAddress().getValue().getLines()).isEqualTo(lines);
    assertThat(result.getAddress().getValue().getPostCode()).isEqualTo(postCode);
    assertThat(result.getAddress().getValue().getFromDate()).hasToString(from.toLocalDate().toString());
    assertThat(result.getAddress().getValue().getToDate()).hasToString(to.toLocalDate().toString());
}
 
Example 19
Source Project: verify-service-provider   Source File: AttributeTranslatorTests.java    License: MIT License 5 votes vote down vote up
@Test(expected = FailedToRequestVerifiedException.class)
public void shouldThrowExceptionWhenVerifiedNotRequested() {
    AttributeStatement attributeStatement = anAttributeStatement()
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("firstname")
            .withSimpleStringValue("Bob")
            .build())
        .build();

    AttributeTranslator.translateAttributes(attributeStatement);
}
 
Example 20
Source Project: verify-service-provider   Source File: AttributeTranslatorTests.java    License: MIT License 5 votes vote down vote up
@Test(expected = RequestedOnlyVerifiedException.class)
public void shouldThrowExceptionWhenOnlyRequestingVerified() {
    AttributeStatement attributeStatement = anAttributeStatement()
        .addAttribute(createVerifiedAttribute("firstname_verified", true))
        .build();

    AttributeTranslator.translateAttributes(attributeStatement);
}
 
Example 21
Source Project: carbon-apimgt   Source File: Util.java    License: 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 22
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 23
Source Project: cxf   Source File: ActAsValidator.java    License: Apache License 2.0 5 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();

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

    // The technical user should be in the Subject
    Subject subject = saml2Assertion.getSubject();
    if (subject == null || subject.getNameID() == null
        || !subject.getNameID().getValue().contains("www.client.com")) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

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

    for (AttributeStatement statement : attributeStatements) {
        List<Attribute> attributes = statement.getAttributes();
        for (Attribute attribute : attributes) {
            if (!"CustomActAs".equals(attribute.getName()) && !"ActAs".equals(attribute.getName())) {
                continue;
            }
            for (XMLObject attributeValue : attribute.getAttributeValues()) {
                Element attributeValueElement = attributeValue.getDOM();
                String text = attributeValueElement.getTextContent();
                if (text.contains("alice") || text.contains("bob")) {
                    return validatedCredential;
                }
            }
        }
    }

    throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
}
 
Example 24
Source Project: cxf-fediz   Source File: SAML2CallbackHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void createAndSetStatement(SAMLCallback callback) {
    AuthenticationStatementBean authBean = new AuthenticationStatementBean();
    authBean.setAuthenticationMethod("Password");
    callback.setAuthenticationStatementData(Collections.singletonList(authBean));

    if (attributeStatements != null && !attributeStatements.isEmpty()) {
        List<AttributeStatementBean> attrStatementBeans = new ArrayList<>();

        for (AttributeStatement attrStatement : attributeStatements) {
            AttributeStatementBean attrStatementBean = new AttributeStatementBean();
            List<AttributeBean> attrBeans = new ArrayList<>();

            for (Attribute attribute : attrStatement.getAttributes()) {
                AttributeBean attributeBean = new AttributeBean();
                attributeBean.setQualifiedName(attribute.getName());
                attributeBean.setNameFormat(attribute.getNameFormat());
                List<Object> attributeValues = new ArrayList<>();
                for (XMLObject attrVal : attribute.getAttributeValues()) {
                    attributeValues.add(attrVal.getDOM().getTextContent());
                }
                attributeBean.setAttributeValues(attributeValues);
                attrBeans.add(attributeBean);
            }
            attrStatementBean.setSamlAttributes(attrBeans);
            attrStatementBeans.add(attrStatementBean);
        }
        callback.setAttributeStatementData(attrStatementBeans);
    }
}
 
Example 25
private boolean isUserAccountCreation(List<AttributeStatement> attributeStatements) {
    return !attributeStatements.isEmpty();
}
 
Example 26
Source Project: verify-service-provider   Source File: AttributeTranslatorTests.java    License: MIT License 4 votes vote down vote up
@Test
public void shouldReturnCorrectValuesForSimpleAttributes() {
    String firstName = "Joe";
    String middleName = "Bob";
    String surname = "Bloggs";
    String cycle3 = "123456";

    AttributeStatement attributeStatement = anAttributeStatement()
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("firstname")
            .withSimpleStringValue(firstName)
            .build())
        .addAttribute(createVerifiedAttribute("firstname_verified", true))
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("middlename")
            .withSimpleStringValue(middleName)
            .build())
        .addAttribute(createVerifiedAttribute("middlename_verified", false))
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("surname")
            .withSimpleStringValue(surname)
            .build())
        .addAttribute(createVerifiedAttribute("surname_verified", true))
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("dateofbirth")
            .withSimpleStringValue("1977-07-21")
            .build())
        .addAttribute(createVerifiedAttribute("dateofbirth_verified", true))
        .addAttribute(new SimpleStringAttributeBuilder()
            .withName("cycle_3")
            .withSimpleStringValue(cycle3)
            .build())
        .build();

    Attributes result = AttributeTranslator.translateAttributes(attributeStatement);

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    assertThat(result.getFirstName().getValue()).isEqualTo(firstName);
    assertThat(result.getMiddleName().getValue()).isEqualTo(middleName);
    assertThat(result.getSurname().getValue()).isEqualTo(surname);
    assertThat(result.getDateOfBirth().getValue().format(formatter)).isEqualTo("1977-07-21");
    assertThat(result.getCycle3()).isEqualTo(cycle3);
}
 
Example 27
@Test
public void getGroupingIdentifierListTestCase() throws ParserConfigurationException, IOException, SAXException,
        UnmarshallingException, UserStoreException {

    String claim = "http://wso2.org/claims/organization";
    String organizationValue = "organization";
    SAMLGroupIDExtractorImpl samlGroupIDExtractor = new SAMLGroupIDExtractorImplWrapper();
    Mockito.when(DocumentBuilderFactory.newInstance()).thenReturn(documentBuilderFactory);
    Mockito.when(documentBuilderFactory.newDocumentBuilder()).
            thenReturn(documentBuilder);
    Mockito.when(documentBuilder.parse(samlGroupIDExtractor.getByteArrayInputStream("test"))).
            thenReturn(document);
    Mockito.when(document.getDocumentElement()).thenReturn(element);
    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(XMLObjectProviderRegistrySupport.class);
    Response response = Mockito.mock(Response.class);
    List<Assertion> assertion = new ArrayList();
    Subject subject = Mockito.mock(Subject.class);
    NameID nameID = Mockito.mock(NameID.class);
    Assertion assertion1 = Mockito.mock(Assertion.class);
    assertion.add(assertion1);
    Mockito.when(XMLObjectProviderRegistrySupport.getUnmarshallerFactory()).thenReturn(unmarshallerFactory);
    Mockito.when(unmarshallerFactory.getUnmarshaller(element)).thenReturn(unmarshaller);
    Mockito.when(unmarshaller.unmarshall(element)).thenReturn(response);
    Mockito.when(response.getAssertions()).thenReturn(assertion);
    Mockito.when(assertion.get(0).getSubject()).thenReturn(subject);
    Mockito.when(subject.getNameID()).thenReturn(nameID);
    Mockito.when(nameID.getValue()).thenReturn("user");
    System.setProperty(APIConstants.READ_ORGANIZATION_FROM_SAML_ASSERTION, "true");
    APIManagerConfigurationService apiManagerConfigService = Mockito.mock(APIManagerConfigurationService.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getAPIManagerConfigurationService()).thenReturn(apiManagerConfigService);
    APIManagerConfiguration apiManagerConfig = Mockito.mock(APIManagerConfiguration.class);
    Mockito.when(apiManagerConfigService.getAPIManagerConfiguration()).thenReturn(apiManagerConfig);
    Mockito.when(apiManagerConfig.getFirstProperty(APIConstants.API_STORE_GROUP_EXTRACTOR_CLAIM_URI)).
            thenReturn("http://wso2.org/claims/organization");

    System.setProperty("carbon.home", "");
    PrivilegedCarbonContext carbonContext;
    carbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);

    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(carbonContext);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId()).thenReturn(-1234);
    PowerMockito.doNothing().when(carbonContext).setTenantDomain("carbon.super", true);

    AttributeStatement mockAttributeStatement = PowerMockito.mock(AttributeStatement.class);
    List<AttributeStatement> attributeStatementList = Collections.singletonList(mockAttributeStatement);
    PowerMockito.when(assertion1.getAttributeStatements()).thenReturn(attributeStatementList);

    Attribute mockAttribute = PowerMockito.mock(Attribute.class);
    List<Attribute> attributesList = Collections.singletonList(mockAttribute);
    PowerMockito.when(mockAttributeStatement.getAttributes()).thenReturn(attributesList);

    XMLObject rawAttribute = PowerMockito.mock(XMLObject.class);
    PowerMockito.when(rawAttribute.toString()).thenReturn(organizationValue);
    List<XMLObject> mockedAttributeValues = Collections.singletonList(rawAttribute);
    AttributedStringImpl mockedAttributedStringImpl = new AttributedStringImpl("nameSpaceURI", "elementLocalName",
            "namespacePrefix");
    String sampleAttrValue = "MockedAuthParamSampleAttribute";
    mockedAttributedStringImpl.setValue(sampleAttrValue);
    List<XMLObject> mockedXSSAttributeValues = Collections.singletonList((XMLObject) mockedAttributedStringImpl);
    XSAnyImpl mockedXSAnyImpl = Mockito.mock(XSAnyImpl.class);
    PowerMockito.when(mockedXSAnyImpl.getTextContent()).thenReturn(sampleAttrValue);
    List<XMLObject> mockedXSAnyImplAttributeValues = Collections.singletonList((XMLObject) mockedXSAnyImpl);
    List<XMLObject> multiMockedAttributeValues = Arrays.asList(rawAttribute, PowerMockito.mock(XMLObject.class));
    AuthenticatorsConfiguration.AuthenticatorConfig mockedAuthenticatorConfig = Mockito
            .mock(AuthenticatorsConfiguration.AuthenticatorConfig.class);
    PowerMockito.when(mockAttribute.getAttributeValues())
            .thenReturn(mockedAttributeValues, multiMockedAttributeValues, mockedXSSAttributeValues,
                    mockedXSAnyImplAttributeValues);

    PowerMockito.mockStatic(AuthenticatorsConfiguration.class);
    AuthenticatorsConfiguration mockedAuthenticatorsConfiguration = PowerMockito
            .mock(AuthenticatorsConfiguration.class);
    PowerMockito.when(AuthenticatorsConfiguration.getInstance()).thenReturn(mockedAuthenticatorsConfiguration);
    Map<String, String> mockedConfigParameters = new HashMap<String, String>();
    mockedConfigParameters.put(APIConstants.ORGANIZATION_CLAIM_ATTRIBUTE, claim);
    PowerMockito.when(mockedAuthenticatorConfig.getParameters()).thenReturn(mockedConfigParameters);
    PowerMockito.when(mockedAuthenticatorsConfiguration
            .getAuthenticatorConfig(APIConstants.SAML2_SSO_AUTHENTICATOR_NAME))
            .thenReturn(mockedAuthenticatorConfig);
    PowerMockito.when(mockAttribute.getName()).thenReturn(claim);

    String[] organizations = samlGroupIDExtractor.
            getGroupingIdentifierList("test");
    Assert.assertEquals(organizationValue, organizations[0]);
}
 
Example 28
Source Project: cxf-fediz   Source File: SAML2CallbackHandler.java    License: Apache License 2.0 4 votes vote down vote up
public List<AttributeStatement> getAttributeStatements() {
    return attributeStatements;
}
 
Example 29
Source Project: cxf-fediz   Source File: SAML2CallbackHandler.java    License: Apache License 2.0 4 votes vote down vote up
public void setAttributeStatements(List<AttributeStatement> attributeStatements) {
    this.attributeStatements = attributeStatements;
}