Example usage for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap

List of usage examples for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap

Introduction

In this page you can find the example usage for org.springframework.util LinkedMultiValueMap LinkedMultiValueMap.

Prototype

public LinkedMultiValueMap() 

Source Link

Document

Create a new LinkedMultiValueMap that wraps a LinkedHashMap .

Usage

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static String getClientCredentialsToken(String baseUrl, String clientId, String clientSecret)
        throws Exception {
    RestTemplate template = new RestTemplate();
    template.setRequestFactory(new StatelessRequestFactory());
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("grant_type", "client_credentials");
    formData.add("client_id", clientId);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.set("Authorization",
            "Basic " + new String(Base64.encode(String.format("%s:%s", clientId, clientSecret).getBytes())));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = template.exchange(baseUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity(formData, headers), Map.class);

    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

    @SuppressWarnings("unchecked")
    OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(response.getBody());
    return accessToken.getValue();
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static Map<String, Object> getPasswordToken(String baseUrl, String clientId, String clientSecret,
        String username, String password, String scopes) throws Exception {
    RestTemplate template = new RestTemplate();
    template.getMessageConverters().add(0,
            new StringHttpMessageConverter(java.nio.charset.Charset.forName("UTF-8")));
    template.setRequestFactory(new StatelessRequestFactory());
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("grant_type", "password");
    formData.add("client_id", clientId);
    formData.add("username", username);
    formData.add("password", password);
    formData.add("response_type", "token id_token");
    if (StringUtils.hasText(scopes)) {
        formData.add("scope", scopes);
    }/*from  w ww. j  a v a2  s .c  o m*/
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    headers.set("Authorization",
            "Basic " + new String(Base64.encode(String.format("%s:%s", clientId, clientSecret).getBytes())));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = template.exchange(baseUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity(formData, headers), Map.class);

    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
    return response.getBody();
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static String getClientCredentialsToken(ServerRunning serverRunning, String clientId,
        String clientSecret) throws Exception {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("grant_type", "client_credentials");
    formData.add("client_id", clientId);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.set("Authorization",
            "Basic " + new String(Base64.encode(String.format("%s:%s", clientId, clientSecret).getBytes())));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap("/oauth/token", formData, headers);
    Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

    @SuppressWarnings("unchecked")
    OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(response.getBody());
    return accessToken.getValue();
}

From source file:org.cloudfoundry.identity.uaa.integration.util.IntegrationTestUtils.java

public static Map<String, String> getAuthorizationCodeTokenMap(ServerRunning serverRunning,
        UaaTestAccounts testAccounts, String clientId, String clientSecret, String username, String password,
        String tokenResponseType, String jSessionId, String redirectUri, boolean callCheckToken)
        throws Exception {
    // TODO Fix to use json API rather than HTML
    HttpHeaders headers = new HttpHeaders();
    if (StringUtils.hasText(jSessionId)) {
        headers.add("Cookie", "JSESSIONID=" + jSessionId);
    }/* w  w  w  .j  av  a 2s .  c om*/
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    String mystateid = "mystateid";
    ServerRunning.UriBuilder builder = serverRunning.buildUri("/oauth/authorize")
            .queryParam("response_type", "code").queryParam("state", mystateid)
            .queryParam("client_id", clientId);
    if (StringUtils.hasText(redirectUri)) {
        builder = builder.queryParam("redirect_uri", redirectUri);
    }
    URI uri = builder.build();

    ResponseEntity<Void> result = serverRunning.createRestTemplate().exchange(uri.toString(), HttpMethod.GET,
            new HttpEntity<>(null, headers), Void.class);

    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = result.getHeaders().getLocation().toString();

    if (result.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : result.getHeaders().get("Set-Cookie")) {
            assertNotNull("Expected cookie in " + result.getHeaders(), cookie);
            headers.add("Cookie", cookie);
        }
    }

    ResponseEntity<String> response = serverRunning.getForString(location, headers);

    if (response.getHeaders().containsKey("Set-Cookie")) {
        for (String cookie : response.getHeaders().get("Set-Cookie")) {
            headers.add("Cookie", cookie);
        }
    }

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    if (!StringUtils.hasText(jSessionId)) {
        // should be directed to the login screen...
        assertTrue(response.getBody().contains("/login.do"));
        assertTrue(response.getBody().contains("username"));
        assertTrue(response.getBody().contains("password"));
        String csrf = IntegrationTestUtils.extractCookieCsrf(response.getBody());

        formData.add("username", username);
        formData.add("password", password);
        formData.add(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, csrf);

        // Should be redirected to the original URL, but now authenticated
        result = serverRunning.postForResponse("/login.do", headers, formData);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());

        headers.remove("Cookie");
        if (result.getHeaders().containsKey("Set-Cookie")) {
            for (String cookie : result.getHeaders().get("Set-Cookie")) {
                headers.add("Cookie", cookie);
            }
        }
    }

    response = serverRunning.createRestTemplate().exchange(result.getHeaders().getLocation().toString(),
            HttpMethod.GET, new HttpEntity<>(null, headers), String.class);

    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("<h1>Application Authorization</h1>"));

        formData.clear();
        formData.add(USER_OAUTH_APPROVAL, "true");
        formData.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody()));
        result = serverRunning.postForResponse("/oauth/authorize", headers, formData);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        location = result.getHeaders().getLocation().toString();
    } else {
        // Token cached so no need for second approval
        assertEquals(HttpStatus.FOUND, response.getStatusCode());
        location = response.getHeaders().getLocation().toString();
    }
    if (StringUtils.hasText(redirectUri)) {
        assertTrue("Wrong location: " + location, location.matches(redirectUri + ".*code=.+"));
    }

    formData.clear();
    formData.add("client_id", clientId);
    formData.add("grant_type", "authorization_code");
    if (StringUtils.hasText(redirectUri)) {
        formData.add("redirect_uri", redirectUri);
    }
    if (StringUtils.hasText(tokenResponseType)) {
        formData.add("response_type", tokenResponseType);
    }
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    tokenHeaders.set("Authorization", testAccounts.getAuthorizationHeader(clientId, clientSecret));
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    @SuppressWarnings("unchecked")
    OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(tokenResponse.getBody());
    Map<String, String> body = tokenResponse.getBody();

    formData = new LinkedMultiValueMap<>();
    headers.set("Authorization", testAccounts.getAuthorizationHeader(clientId, clientSecret));
    formData.add("token", accessToken.getValue());

    if (callCheckToken) {
        tokenResponse = serverRunning.postForMap("/check_token", formData, headers);
        assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
        //System.err.println(tokenResponse.getBody());
        assertNotNull(tokenResponse.getBody().get("iss"));
    }
    return body;
}

From source file:org.cloudfoundry.identity.uaa.login.saml.LoginSamlAuthenticationProvider.java

public MultiValueMap<String, String> retrieveUserAttributes(SamlIdentityProviderDefinition definition,
        SAMLCredential credential) {//  w  w w.ja v  a 2s .c o m
    MultiValueMap<String, String> userAttributes = new LinkedMultiValueMap<>();
    if (definition != null && definition.getAttributeMappings() != null) {
        for (Entry<String, Object> attributeMapping : definition.getAttributeMappings().entrySet()) {
            if (attributeMapping.getValue() instanceof String) {
                if (credential.getAttribute((String) attributeMapping.getValue()) != null) {
                    String key = attributeMapping.getKey();
                    int count = 0;
                    for (XMLObject xmlObject : credential.getAttribute((String) attributeMapping.getValue())
                            .getAttributeValues()) {
                        if (xmlObject instanceof XSString) {
                            String value = ((XSString) xmlObject).getValue();
                            userAttributes.add(key, value);
                        } else {
                            logger.debug(String.format(
                                    "SAML user attribute %s at index %s is not of type XSString [zone:%s, origin:%s]",
                                    key, count, definition.getZoneId(), definition.getIdpEntityAlias()));
                        }
                        count++;
                    }
                }
            }
        }
    }
    return userAttributes;
}

From source file:org.cloudfoundry.identity.uaa.oauth.RemoteTokenServices.java

@Override
public OAuth2Authentication loadAuthentication(String accessToken) throws AuthenticationException {

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("token", accessToken);
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret));
    Map<String, Object> map = postForMap(checkTokenEndpointUrl, formData, headers);

    if (map.containsKey("error")) {
        logger.debug("check_token returned error: " + map.get("error"));
        throw new InvalidTokenException(accessToken);
    }//from   w w w.j a v  a2 s  .  com

    Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server");
    String remoteClientId = (String) map.get("client_id");

    Set<String> scope = new HashSet<String>();
    if (map.containsKey("scope")) {
        @SuppressWarnings("unchecked")
        Collection<String> values = (Collection<String>) map.get("scope");
        scope.addAll(values);
    }
    AuthorizationRequest clientAuthentication = new AuthorizationRequest(remoteClientId, scope);

    if (map.containsKey("resource_ids") || map.containsKey("client_authorities")) {
        Set<String> resourceIds = new HashSet<String>();
        if (map.containsKey("resource_ids")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("resource_ids");
            resourceIds.addAll(values);
        }
        Set<GrantedAuthority> clientAuthorities = new HashSet<GrantedAuthority>();
        if (map.containsKey("client_authorities")) {
            @SuppressWarnings("unchecked")
            Collection<String> values = (Collection<String>) map.get("client_authorities");
            clientAuthorities.addAll(getAuthorities(values));
        }
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId(remoteClientId);
        clientDetails.setResourceIds(resourceIds);
        clientDetails.setAuthorities(clientAuthorities);
        clientAuthentication.setResourceIdsAndAuthoritiesFromClientDetails(clientDetails);
    }
    Map<String, String> requestParameters = new HashMap<>();
    if (isStoreClaims()) {
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null && entry.getValue() instanceof String) {
                requestParameters.put(entry.getKey(), (String) entry.getValue());
            }
        }
    }

    if (map.containsKey(ClaimConstants.ADDITIONAL_AZ_ATTR)) {
        try {
            requestParameters.put(ClaimConstants.ADDITIONAL_AZ_ATTR,
                    JsonUtils.writeValueAsString(map.get(ClaimConstants.ADDITIONAL_AZ_ATTR)));
        } catch (JsonUtils.JsonUtilException e) {
            throw new IllegalStateException("Cannot convert access token to JSON", e);
        }
    }
    clientAuthentication.setRequestParameters(Collections.unmodifiableMap(requestParameters));

    Authentication userAuthentication = getUserAuthentication(map, scope);

    clientAuthentication.setApproved(true);
    return new OAuth2Authentication(clientAuthentication.createOAuth2Request(), userAuthentication);
}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManager.java

@Override
protected void populateAuthenticationAttributes(UaaAuthentication authentication, Authentication request,
        AuthenticationData authenticationData) {
    Map<String, Object> claims = authenticationData.getClaims();
    if (claims != null) {
        if (claims.get("amr") != null) {
            if (authentication.getAuthenticationMethods() == null) {
                authentication.setAuthenticationMethods(new HashSet<>((Collection<String>) claims.get("amr")));
            } else {
                authentication.getAuthenticationMethods().addAll((Collection<String>) claims.get("amr"));
            }/*from   w  w  w .  ja  va 2  s . c om*/
        }

        Object acr = claims.get(ClaimConstants.ACR);
        if (acr != null) {
            if (acr instanceof Map) {
                Map<String, Object> acrMap = (Map) acr;
                Object values = acrMap.get("values");
                if (values instanceof Collection) {
                    authentication.setAuthContextClassRef(new HashSet<>((Collection) values));
                } else if (values instanceof String[]) {
                    authentication.setAuthContextClassRef(new HashSet<>(Arrays.asList((String[]) values)));
                } else {
                    logger.debug(String.format("Unrecognized ACR claim[%s] for user_id: %s", values,
                            authentication.getPrincipal().getId()));
                }
            } else if (acr instanceof String) {
                authentication.setAuthContextClassRef(new HashSet(Arrays.asList((String) acr)));
            } else {
                logger.debug(String.format("Unrecognized ACR claim[%s] for user_id: %s", acr,
                        authentication.getPrincipal().getId()));
            }
        }
        MultiValueMap<String, String> userAttributes = new LinkedMultiValueMap<>();
        logger.debug("Mapping XOauth custom attributes");
        for (Map.Entry<String, Object> entry : authenticationData.getAttributeMappings().entrySet()) {
            if (entry.getKey().startsWith(USER_ATTRIBUTE_PREFIX) && entry.getValue() != null) {
                String key = entry.getKey().substring(USER_ATTRIBUTE_PREFIX.length());
                Object values = claims.get(entry.getValue());
                if (values != null) {
                    logger.debug(String.format("Mapped XOauth attribute %s to %s", key, values));
                    if (values instanceof List) {
                        List list = (List) values;
                        List<String> strings = (List<String>) list.stream()
                                .map(object -> Objects.toString(object, null)).collect(Collectors.toList());
                        userAttributes.put(key, strings);
                    } else if (values instanceof String) {
                        userAttributes.put(key, Arrays.asList((String) values));
                    } else {
                        userAttributes.put(key, Arrays.asList(values.toString()));
                    }
                }
            }
        }
        authentication.setUserAttributes(userAttributes);
        authentication.setExternalGroups(ofNullable(authenticationData.getAuthorities()).orElse(emptyList())
                .stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet()));
    }

    super.populateAuthenticationAttributes(authentication, request, authenticationData);
}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManager.java

private JsonWebKeySet<JsonWebKey> getTokenKeyFromOAuth(AbstractXOAuthIdentityProviderDefinition config) {
    String tokenKey = config.getTokenKey();
    if (StringUtils.hasText(tokenKey)) {
        Map<String, Object> p = new HashMap<>();
        p.put("value", tokenKey);
        p.put("kty", KeyInfo.isAssymetricKey(tokenKey) ? RSA.name() : MAC.name());
        logger.debug("Key configured, returning.");
        return new JsonWebKeySet<>(Arrays.asList(new JsonWebKey(p)));
    }// w  w w. j  a v  a  2 s . c  o m
    URL tokenKeyUrl = config.getTokenKeyUrl();
    if (tokenKeyUrl == null || !StringUtils.hasText(tokenKeyUrl.toString())) {
        return new JsonWebKeySet<>(Collections.emptyList());
    }

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
    headers.add("Authorization", getClientAuthHeader(config));
    headers.add("Accept", "application/json");
    HttpEntity tokenKeyRequest = new HttpEntity<>(null, headers);
    logger.debug("Fetching token keys from:" + tokenKeyUrl);
    ResponseEntity<String> responseEntity = getRestTemplate(config).exchange(tokenKeyUrl.toString(),
            HttpMethod.GET, tokenKeyRequest, String.class);
    logger.debug("Token key response:" + responseEntity.getStatusCode());
    if (responseEntity.getStatusCode() == HttpStatus.OK) {
        return JsonWebKeyHelper.deserialize(responseEntity.getBody());
    } else {
        throw new InvalidTokenException(
                "Unable to fetch verification keys, status:" + responseEntity.getStatusCode());
    }
}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManagerIT.java

@Test
public void test_custom_user_attributes_are_stored() {
    addTheUserOnAuth();//from w  ww  .j  a  v a2  s .  c o m

    List<String> managers = Arrays.asList("Sue the Sloth", "Kari the AntEater");
    List<String> costCenter = Collections.singletonList("Austin, TX");
    claims.put("managers", managers);
    claims.put("employeeCostCenter", costCenter);
    attributeMappings.put("user.attribute.costCenter", "employeeCostCenter");
    attributeMappings.put("user.attribute.terribleBosses", "managers");
    config.setStoreCustomAttributes(true);
    config.setExternalGroupsWhitelist(Collections.singletonList("*"));
    List<String> scopes = SCOPES_LIST;
    claims.put("scope", scopes);
    attributeMappings.put(GROUP_ATTRIBUTE_NAME, "scope");
    mockToken();
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.put("costCenter", costCenter);
    map.put("terribleBosses", managers);

    UaaAuthentication authentication = (UaaAuthentication) xoAuthAuthenticationManager.authenticate(xCodeToken);

    assertEquals(map, authentication.getUserAttributes());
    assertThat(authentication.getExternalGroups(), containsInAnyOrder(scopes.toArray()));
    UserInfo info = new UserInfo().setUserAttributes(map).setRoles(scopes);
    UserInfo actualUserInfo = xoAuthAuthenticationManager.getUserDatabase()
            .getUserInfo(authentication.getPrincipal().getId());
    assertEquals(actualUserInfo.getUserAttributes(), info.getUserAttributes());
    assertThat(actualUserInfo.getRoles(), containsInAnyOrder(info.getRoles().toArray()));

    UaaUser actualUser = xoAuthAuthenticationManager.getUserDatabase().retrieveUserByName("12345",
            "the_origin");
    assertThat(actualUser, is(not(nullValue())));
    assertThat(actualUser.getGivenName(), is("Marissa"));
}

From source file:org.cloudfoundry.identity.uaa.provider.oauth.XOAuthAuthenticationManagerTest.java

@Test
public void test_custom_user_attributes_are_stored() throws Exception {
    addTheUserOnAuth();//ww  w  .j a  v a2 s. co  m

    List<String> managers = Arrays.asList("Sue the Sloth", "Kari the AntEater");
    List<String> costCenter = Arrays.asList("Austin, TX");
    claims.put("managers", managers);
    claims.put("employeeCostCenter", costCenter);
    attributeMappings.put("user.attribute.costCenter", "employeeCostCenter");
    attributeMappings.put("user.attribute.terribleBosses", "managers");
    config.setStoreCustomAttributes(true);
    config.setExternalGroupsWhitelist(Arrays.asList("*"));
    List<String> scopes = Arrays.asList("openid", "some.other.scope", "closedid");
    claims.put("scope", scopes);
    attributeMappings.put(GROUP_ATTRIBUTE_NAME, "scope");
    mockToken();
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.put("costCenter", costCenter);
    map.put("terribleBosses", managers);
    UaaAuthentication authentication = (UaaAuthentication) xoAuthAuthenticationManager.authenticate(xCodeToken);
    assertEquals(map, authentication.getUserAttributes());
    assertThat(authentication.getExternalGroups(), containsInAnyOrder(scopes.toArray()));
    UserInfo info = new UserInfo().setUserAttributes(map).setRoles(scopes);
    UserInfo actualUserInfo = xoAuthAuthenticationManager.getUserDatabase()
            .getUserInfo(authentication.getPrincipal().getId());
    assertEquals(actualUserInfo.getUserAttributes(), info.getUserAttributes());
    assertThat(actualUserInfo.getRoles(), containsInAnyOrder(info.getRoles().toArray()));

}