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

The following examples show how to use org.opensaml.saml.saml2.core.Attribute. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SamlClient.java    From saml-client with 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 #2
Source File: UnsignedAssertionResponseHandlerTest.java    From verify-service-provider with MIT License 6 votes vote down vote up
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 File: AttributeTranslatorTests.java    From verify-service-provider with 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 #4
Source File: SAML2CallbackHandler.java    From cxf-fediz with 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 #5
Source File: MockSamlIdpServer.java    From deprecated-security-advanced-modules with Apache License 2.0 5 votes vote down vote up
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 File: AbstractSTSTest.java    From cxf-fediz with 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 #7
Source File: SAMLClaimsTest.java    From cxf with 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 #8
Source File: ActAsValidator.java    From cxf with 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 #9
Source File: SAMLGroupIDExtractorImpl.java    From carbon-apimgt with 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 #10
Source File: Util.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * Get the username from the SAML2 Assertion
 *
 * @param assertion SAML2 assertion
 * @return username
 */
public static String getUsernameFromAssertion(Assertion assertion, String usernameAttribute) {
    String username = null;
    if (!StringUtils.isEmpty(usernameAttribute)) {
        // There can be multiple AttributeStatements in Assertion
        List<AttributeStatement> attributeStatements = assertion.getAttributeStatements();
        if (attributeStatements != null) {
            for (AttributeStatement attributeStatement : attributeStatements) {
                // There can be multiple Attributes in an attributeStatement
                List<Attribute> attributes = attributeStatement.getAttributes();
                if (attributes != null) {
                    for (Attribute attribute : attributes) {
                        String attributeName = attribute.getDOM().getAttribute(SSOConstants.SAML_NAME_ATTRIBUTE);
                        if (attributeName.equals(usernameAttribute)) {
                            List<XMLObject> attributeValues = attribute.getAttributeValues();
                            // There can be multiple attribute values in an attribute, but get the first one
                            username = attributeValues.get(0).getDOM().getTextContent();
                            if (log.isDebugEnabled()) {
                                log.debug("Name of authenticated user from SAML response : " + username);
                            }
                        }
                    }
                }
            }
        }
    } else {
        Subject subject = assertion.getSubject();
        if (subject != null) {
            if (subject.getNameID() != null) {
                username = subject.getNameID().getValue();
                if (log.isDebugEnabled()) {
                    log.debug("Name of authenticated user from SAML response : " + username);
                }
            }
        }
    }
    return username;
}
 
Example #11
Source File: SamlResponseHelper.java    From verify-service-provider with 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 #12
Source File: AuthnRequestFactoryTest.java    From verify-service-provider with 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 #13
Source File: UnsignedAssertionResponseHandlerTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
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 #14
Source File: VerifyAssertionTranslatorTest.java    From verify-service-provider with MIT License 5 votes vote down vote up
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
Source File: AttributeTranslatorTests.java    From verify-service-provider with 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 #16
Source File: AttributeTranslatorTests.java    From verify-service-provider with 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 #17
Source File: AttributeTranslator.java    From verify-service-provider with 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 #18
Source File: AttributeTranslator.java    From verify-service-provider with 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 #19
Source File: AttributeTranslator.java    From verify-service-provider with 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 #20
Source File: AssertionHelper.java    From verify-service-provider with 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 #21
Source File: AttributeTranslator.java    From verify-service-provider with 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 #22
Source File: AuthnRequestFactory.java    From verify-service-provider with 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 #23
Source File: AuthnRequestFactory.java    From verify-service-provider with 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 #24
Source File: AttributeTranslator.java    From verify-service-provider with 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 #25
Source File: UnsignedAssertionsResponseHandler.java    From verify-service-provider with MIT License 4 votes vote down vote up
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();
}
 
Example #26
Source File: AttributeTranslator.java    From verify-service-provider with 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 #27
Source File: AttributeTranslator.java    From verify-service-provider with 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 File: SAMLGroupIDExtractorImplTest.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@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 #29
Source File: AttributeTranslator.java    From verify-service-provider with 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 #30
Source File: AttributeTranslator.java    From verify-service-provider with 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);
}