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

The following examples show how to use org.opensaml.saml.saml2.core.Attribute. 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
private Attribute createEncryptedAssertionKeysAttribute(List<String> keys) {
    List<EncryptedAssertionKeys> assertionKeysValues = new ArrayList<>();
    for (String key : keys) {
        EncryptedAssertionKeys attributeValue = new EncryptedAssertionKeysBuilder().buildObject();
        attributeValue.setValue(key);
        assertionKeysValues.add(attributeValue);
    }

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

    attribute.getAttributeValues().addAll(assertionKeysValues);
    return attribute;
}
 
Example 3
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 4
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 5
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 6
Source Project: verify-service-provider   Source File: AttributeTranslator.java    License: MIT License 5 votes vote down vote up
private static Optional<List<VerifiableAttribute<Address>>> getVerifiableAddressListAttribute(List<Attribute> statementAttributes, String attributeName) {
    final Optional<Attribute> attribute = getAttribute(statementAttributes, attributeName);
    return attribute.map(
        attr -> attr.getAttributeValues().stream().map(
            val -> toVerifiableAddress((AddressImpl) val)
        ).collect(Collectors.toList())
    );
}
 
Example 7
Source Project: verify-service-provider   Source File: AttributeTranslator.java    License: MIT License 5 votes vote down vote up
private static Optional<String> getStringAttributeValue(List<Attribute> attributes, String attributeName) {
    final Optional<Attribute> attribute = getAttribute(attributes, attributeName);
    return attribute.map(attr -> {
        StringValueSamlObject attributeValue = ((StringValueSamlObject) attr.getAttributeValues().get(0));
        return Optional.ofNullable(attributeValue.getValue()).orElse("");
    });
}
 
Example 8
Source Project: verify-service-provider   Source File: AttributeTranslator.java    License: MIT License 5 votes vote down vote up
private static Optional<LocalDate> getDateAttributeValue(List<Attribute> attributes, String attributeName) {
    return getStringAttributeValue(attributes, attributeName).map(x -> {
        try {
            return LocalDate.parse(x, DateTimeFormatter.ISO_DATE);
        } catch (DateTimeParseException e) {
            throw new SamlResponseValidationException(
                String.format("Error in SAML date format for attribute '%s'. Expected ISO date format, got: '%s'",
                    attributeName,
                    e.getParsedString())
            );
        }
    });
}
 
Example 9
Source Project: verify-service-provider   Source File: AuthnRequestFactory.java    License: MIT License 5 votes vote down vote up
private Extensions createExtensions() {
    Extensions extensions = new ExtensionsBuilder().buildObject();
    Attribute versionsAttribute = new AttributeBuilder().buildObject();
    versionsAttribute.setName("Versions");
    versionsAttribute.getAttributeValues().add(createApplicationVersion());
    extensions.getUnknownXMLObjects().add(encrypt(versionsAttribute));
    return extensions;
}
 
Example 10
Source Project: verify-service-provider   Source File: AuthnRequestFactory.java    License: MIT License 5 votes vote down vote up
private EncryptedAttribute encrypt(Attribute attribute) {
    try {
        return encrypterFactory.createEncrypter().encrypt(attribute);
    } catch (EncryptionException e) {
        throw new RuntimeException(e);
    }
}
 
Example 11
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 12
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 13
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 14
private static AssertionBuilder aMatchingDatasetAssertionWithSignature(List<Attribute> attributes, Signature signature, String requestId) {
    return anAssertion()
            .withId("mds-assertion")
            .withIssuer(anIssuer().withIssuerId(STUB_IDP_ONE).build())
            .withSubject(anAssertionSubject(requestId))
            .withSignature(signature)
            .addAttributeStatement(anAttributeStatement().addAllAttributes(attributes).build())
            .withConditions(aConditions().build());
}
 
Example 15
private Attribute createCountrySamlResponseAttribute(String countrySaml) {
    CountrySamlResponse attributeValue = new CountrySamlResponseBuilder().buildObject();
    attributeValue.setValue(countrySaml);

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

    attribute.getAttributeValues().add(attributeValue);
    return attribute;
}
 
Example 16
Source Project: verify-service-provider   Source File: AuthnRequestFactoryTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldAddApplicationVersionInExtension() throws Exception {
    when(manifestReader.getAttributeValueFor(VerifyServiceProviderApplication.class, "Version")).thenReturn("some-version");

    AuthnRequest authnRequest = factory.build(SERVICE_ENTITY_ID);

    Extensions extensions = authnRequest.getExtensions();
    EncryptedAttribute encryptedAttribute = (EncryptedAttribute) extensions.getUnknownXMLObjects().get(0);

    Attribute attribute = decrypter.decrypt(encryptedAttribute);
    Version version = (Version) attribute.getAttributeValues().get(0);

    assertThat(attribute.getName()).isEqualTo("Versions");
    assertThat(version.getApplicationVersion().getValue()).isEqualTo("some-version");
}
 
Example 17
Source Project: verify-service-provider   Source File: SamlResponseHelper.java    License: MIT License 5 votes vote down vote up
public static Attribute createVerifiedAttribute(String name, boolean value) {
    Attribute attribute = new OpenSamlXmlObjectFactory().createAttribute();
    attribute.setName(name);

    XMLObjectBuilderFactory builderFactory = XMLObjectProviderRegistrySupport.getBuilderFactory();
    Verified verifiedValue = (Verified) builderFactory.getBuilder(Verified.TYPE_NAME).buildObject(Verified.DEFAULT_ELEMENT_NAME, Verified.TYPE_NAME);
    verifiedValue.setValue(value);

    attribute.getAttributeValues().add(verifiedValue);

    return attribute;
}
 
Example 18
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 19
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 20
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 21
Source Project: cxf   Source File: SAMLClaimsTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test the creation of a SAML2 Assertion with StaticClaimsHandler
 */
@org.junit.Test
public void testSaml2StaticClaims() throws Exception {
    TokenProvider samlTokenProvider = new SAMLTokenProvider();
    TokenProviderParameters providerParameters =
        createProviderParameters(WSS4JConstants.WSS_SAML2_TOKEN_TYPE, STSConstants.BEARER_KEY_KEYTYPE, null);

    ClaimsManager claimsManager = new ClaimsManager();
    StaticClaimsHandler claimsHandler = new StaticClaimsHandler();
    Map<String, String> staticClaimsMap = new HashMap<>();
    staticClaimsMap.put(CLAIM_STATIC_COMPANY, CLAIM_STATIC_COMPANY_VALUE);
    claimsHandler.setGlobalClaims(staticClaimsMap);
    claimsManager.setClaimHandlers(Collections.singletonList((ClaimsHandler)claimsHandler));
    providerParameters.setClaimsManager(claimsManager);

    ClaimCollection claims = new ClaimCollection();
    Claim claim = new Claim();
    claim.setClaimType(CLAIM_STATIC_COMPANY);
    claims.add(claim);
    providerParameters.setRequestedPrimaryClaims(claims);

    assertTrue(samlTokenProvider.canHandleToken(WSS4JConstants.WSS_SAML2_TOKEN_TYPE));
    TokenProviderResponse providerResponse = samlTokenProvider.createToken(providerParameters);
    assertNotNull(providerResponse);
    assertTrue(providerResponse.getToken() != null && providerResponse.getTokenId() != null);

    Element token = (Element)providerResponse.getToken();
    String tokenString = DOM2Writer.nodeToString(token);
    assertTrue(tokenString.contains(providerResponse.getTokenId()));
    assertTrue(tokenString.contains("AttributeStatement"));
    assertTrue(tokenString.contains("alice"));
    assertTrue(tokenString.contains(SAML2Constants.CONF_BEARER));

    SamlAssertionWrapper assertion = new SamlAssertionWrapper(token);
    List<Attribute> attributes = assertion.getSaml2().getAttributeStatements().get(0).getAttributes();
    assertEquals(attributes.size(), 1);
    assertEquals(attributes.get(0).getName(), CLAIM_STATIC_COMPANY);
    XMLObject valueObj = attributes.get(0).getAttributeValues().get(0);
    assertEquals(valueObj.getDOM().getTextContent(), CLAIM_STATIC_COMPANY_VALUE);
}
 
Example 22
Source Project: cxf-fediz   Source File: AbstractSTSTest.java    License: Apache License 2.0 5 votes vote down vote up
protected void validateIssuedClaims(List<Attribute> attributes, Properties props) {
    for (Attribute attribute: attributes) {
        String expectedValue = (String)props.get(attribute.getName());
        Assert.assertNotNull("Claim '" + attribute.getName() + "' not configured in properties file",
                             expectedValue);
        String value = attribute.getAttributeValues().get(0).getDOM().getTextContent();
        Assert.assertEquals("Expected claim value '" + expectedValue + "' [" + value + "]", expectedValue, value);
    }
}
 
Example 23
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 24
Source Project: verify-service-provider   Source File: AttributeTranslator.java    License: MIT License 4 votes vote down vote up
private static VerifiableAttribute<String> getVerifiableStringAttribute(List<Attribute> statementAttributes, String attributeName, String attributeVerifiedName) {
    final Optional<String> attributeValue = getStringAttributeValue(statementAttributes, attributeName);
    final Optional<Boolean> attributeVerified = getBooleanAttributeValue(statementAttributes, attributeVerifiedName);
    return VerifiableAttribute.fromOptionals(attributeValue, attributeVerified);
}
 
Example 25
Source Project: verify-service-provider   Source File: AttributeTranslator.java    License: MIT License 4 votes vote down vote up
private static VerifiableAttribute<LocalDate> getVerifiableDateAttribute(List<Attribute> statementAttributes, String attributeName, String attributeVerifiedName) {
    final Optional<LocalDate> attributeValue = getDateAttributeValue(statementAttributes, attributeName);
    final Optional<Boolean> attributeVerified = getBooleanAttributeValue(statementAttributes, attributeVerifiedName);
    return VerifiableAttribute.fromOptionals(attributeValue, attributeVerified);
}
 
Example 26
Source Project: verify-service-provider   Source File: AttributeTranslator.java    License: MIT License 4 votes vote down vote up
private static VerifiableAttribute<Address> getVerifiableAddressAttribute(List<Attribute> statementAttributes, String attributeName, String attributeVerifiedName) {
    final Optional<Address> attributeValue = getAddressAttributeValue(statementAttributes, attributeName);
    final Optional<Boolean> attributeVerified = getBooleanAttributeValue(statementAttributes, attributeVerifiedName);
    return VerifiableAttribute.fromOptionals(attributeValue, attributeVerified);
}
 
Example 27
Source Project: verify-service-provider   Source File: AttributeTranslator.java    License: MIT License 4 votes vote down vote up
private static Optional<Attribute> getAttribute(List<Attribute> attributes, String name) {
    return attributes.stream().filter(a -> a.getName().equals(name)).findFirst();
}
 
Example 28
Source Project: verify-service-provider   Source File: AttributeTranslator.java    License: MIT License 4 votes vote down vote up
private static Optional<Boolean> getBooleanAttributeValue(List<Attribute> attributes, String attributeName) {
    final Optional<Attribute> attribute = getAttribute(attributes, attributeName);
    return attribute.map(attr -> ((Verified) attr.getAttributeValues().get(0)).getValue());
}
 
Example 29
Source Project: verify-service-provider   Source File: AttributeTranslator.java    License: MIT License 4 votes vote down vote up
private static Optional<Address> getAddressAttributeValue(List<Attribute> attributes, String attributeName) {
    final Optional<Attribute> attribute = getAttribute(attributes, attributeName);
    return attribute.map(attr -> toAddress((AddressImpl) attr.getAttributeValues().get(0)));
}
 
Example 30
private String getCountryResponseStringFromAssertion(Assertion hubResponseAssertion) {
    List<Attribute> attributes = hubResponseAssertion.getAttributeStatements().get(ONLY_ONE_PRESENT).getAttributes();
    CountrySamlResponse countrySamlResponse = (CountrySamlResponse) attributes.get(ONLY_ONE_PRESENT).getAttributeValues().get(ONLY_ONE_PRESENT);
    return countrySamlResponse.getValue();
}