Example usage for org.springframework.util MultiValueMap add

List of usage examples for org.springframework.util MultiValueMap add

Introduction

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

Prototype

void add(K key, @Nullable V value);

Source Link

Document

Add the given single value to the current list of values for the given key.

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);
    }/*  ww  w.  j a v a  2  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);
    }//from  w  w w  .  j a  va 2s  .  co  m
    // 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) {//from   ww  w.jav  a 2 s.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.login.saml.LoginSamlAuthenticationProvider.java

protected UaaUser createIfMissing(UaaPrincipal samlPrincipal, boolean addNew,
        Collection<? extends GrantedAuthority> authorities, MultiValueMap<String, String> userAttributes) {
    UaaUser user = null;//from ww  w  . jav a  2 s. c o  m
    String invitedUserId = null;
    boolean is_invitation_acceptance = isAcceptedInvitationAuthentication();
    if (is_invitation_acceptance) {
        invitedUserId = (String) RequestContextHolder.currentRequestAttributes().getAttribute("user_id",
                RequestAttributes.SCOPE_SESSION);
        user = userDatabase.retrieveUserById(invitedUserId);
        if (userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME) != null) {
            if (!userAttributes.getFirst(EMAIL_ATTRIBUTE_NAME).equalsIgnoreCase(user.getEmail())) {
                throw new BadCredentialsException(
                        "SAML User email mismatch. Authenticated email doesn't match invited email.");
            }
        } else {
            userAttributes = new LinkedMultiValueMap<>(userAttributes);
            userAttributes.add(EMAIL_ATTRIBUTE_NAME, user.getEmail());
        }
        addNew = false;
        if (user.getUsername().equals(user.getEmail()) && !user.getUsername().equals(samlPrincipal.getName())) {
            user.setVerified(true);
            user = user.modifyUsername(samlPrincipal.getName());
        }
        publish(new InvitedUserAuthenticatedEvent(user));
        user = userDatabase.retrieveUserById(invitedUserId);
    }

    boolean userModified = false;
    UaaUser userWithSamlAttributes = getUser(samlPrincipal, userAttributes);
    try {
        if (user == null) {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        }
    } catch (UsernameNotFoundException e) {
        if (!addNew) {
            throw new LoginSAMLException("SAML user does not exist. "
                    + "You can correct this by creating a shadow user for the SAML user.", e);
        }
        // Register new users automatically
        publish(new NewUserAuthenticatedEvent(userWithSamlAttributes));
        try {
            user = userDatabase.retrieveUserByName(samlPrincipal.getName(), samlPrincipal.getOrigin());
        } catch (UsernameNotFoundException ex) {
            throw new BadCredentialsException(
                    "Unable to establish shadow user for SAML user:" + samlPrincipal.getName());
        }
    }
    if (haveUserAttributesChanged(user, userWithSamlAttributes)) {
        userModified = true;
        user = user.modifyAttributes(userWithSamlAttributes.getEmail(), userWithSamlAttributes.getGivenName(),
                userWithSamlAttributes.getFamilyName(), userWithSamlAttributes.getPhoneNumber());
    }
    publish(new ExternalGroupAuthorizationEvent(user, userModified, authorities, true));
    user = userDatabase.retrieveUserById(user.getId());
    UaaPrincipal result = new UaaPrincipal(user);
    Authentication success = new UaaAuthentication(result, user.getAuthorities(), null);
    publish(new UserAuthenticationSuccessEvent(user, success));
    return user;
}

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);
    }/*w  w  w.j a v a2s.  co m*/

    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

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)));
    }/*from ww  w.j a v a  2  s  .  c om*/
    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.XOAuthAuthenticationManager.java

private String getTokenFromCode(XOAuthCodeToken codeToken, AbstractXOAuthIdentityProviderDefinition config) {
    if (StringUtils.hasText(codeToken.getIdToken()) && "id_token".equals(getResponseType(config))) {
        logger.debug("XOauthCodeToken contains id_token, not exchanging code.");
        return codeToken.getIdToken();
    }/*from  w  ww .j  av a2 s. co  m*/
    MultiValueMap<String, String> body = new LinkedMaskingMultiValueMap<>("code");
    body.add("grant_type", "authorization_code");
    body.add("response_type", getResponseType(config));
    body.add("code", codeToken.getCode());
    body.add("redirect_uri", codeToken.getRedirectUrl());

    HttpHeaders headers = new HttpHeaders();
    String clientAuthHeader = getClientAuthHeader(config);
    headers.add("Authorization", clientAuthHeader);
    headers.add("Accept", "application/json");

    URI requestUri;
    HttpEntity requestEntity = new HttpEntity<>(body, headers);
    try {
        requestUri = config.getTokenUrl().toURI();
    } catch (URISyntaxException e) {
        logger.error("Invalid URI configured:" + config.getTokenUrl(), e);
        return null;
    }

    try {
        logger.debug(String.format("Performing token exchange with url:%s and request:%s", requestUri, body));
        // A configuration that skips SSL/TLS validation requires clobbering the rest template request factory
        // setup by the bean initializer.
        ResponseEntity<Map<String, String>> responseEntity = getRestTemplate(config).exchange(requestUri,
                HttpMethod.POST, requestEntity, new ParameterizedTypeReference<Map<String, String>>() {
                });
        logger.debug(String.format("Request completed with status:%s", responseEntity.getStatusCode()));
        return responseEntity.getBody().get(ID_TOKEN);
    } catch (HttpServerErrorException | HttpClientErrorException ex) {
        throw ex;
    }
}

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

public MultiValueMap<String, String> retrieveUserAttributes(SamlIdentityProviderDefinition definition,
        SAMLCredential credential) {/*from w  w w .  j a v a2s . co  m*/
    logger.debug(String.format("Retrieving SAML user attributes [zone:%s, origin:%s]", definition.getZoneId(),
            definition.getIdpEntityAlias()));
    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();
                    for (XMLObject xmlObject : credential.getAttribute((String) attributeMapping.getValue())
                            .getAttributeValues()) {
                        String value = getStringValue(key, definition, xmlObject);
                        if (value != null) {
                            userAttributes.add(key, value);
                        }
                    }
                }
            }
        }
    }
    if (credential.getAuthenticationAssertion() != null
            && credential.getAuthenticationAssertion().getAuthnStatements() != null) {
        for (AuthnStatement statement : credential.getAuthenticationAssertion().getAuthnStatements()) {
            if (statement.getAuthnContext() != null
                    && statement.getAuthnContext().getAuthnContextClassRef() != null) {
                userAttributes.add(AUTHENTICATION_CONTEXT_CLASS_REFERENCE,
                        statement.getAuthnContext().getAuthnContextClassRef().getAuthnContextClassRef());
            }
        }
    }
    return userAttributes;
}