Example usage for org.springframework.http HttpHeaders setAccept

List of usage examples for org.springframework.http HttpHeaders setAccept

Introduction

In this page you can find the example usage for org.springframework.http HttpHeaders setAccept.

Prototype

public void setAccept(List<MediaType> acceptableMediaTypes) 

Source Link

Document

Set the list of acceptable MediaType media types , as specified by the Accept header.

Usage

From source file:org.cloudfoundry.identity.uaa.integration.CheckTokenEndpointIntegrationTests.java

@SuppressWarnings("unchecked")
private OAuth2AccessToken getUserToken(String optAdditionAttributes) {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.set("client_id", "cf");
    formData.set("client_secret", "");
    formData.set("username", testAccounts.getUserName());
    formData.set("password", testAccounts.getPassword());
    formData.set("response_type", "token");
    formData.set("grant_type", "password");
    formData.set("token_format", "jwt");
    if (optAdditionAttributes != null) {
        formData.set("authorities", optAdditionAttributes);
    }/*from www .j a v  a  2 s  . c  o m*/
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

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

    return DefaultOAuth2AccessToken.valueOf(response.getBody());
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.OpenIdTokenGrantsIT.java

@Test
public void testImplicitGrant() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("source", "credentials");
    postBody.add("username", user.getUserName());
    postBody.add("password", secret);

    ResponseEntity<Void> responseEntity = restOperations.exchange(loginUrl + "/oauth/authorize",
            HttpMethod.POST, new HttpEntity<>(postBody, headers), Void.class);

    Assert.assertEquals(HttpStatus.FOUND, responseEntity.getStatusCode());

    UriComponents locationComponents = UriComponentsBuilder.fromUri(responseEntity.getHeaders().getLocation())
            .build();/*from www  . jav  a 2  s .  com*/
    Assert.assertEquals("uaa.cloudfoundry.com", locationComponents.getHost());
    Assert.assertEquals("/redirect/cf", locationComponents.getPath());

    MultiValueMap<String, String> params = parseFragmentParams(locationComponents);

    Assert.assertThat(params.get("jti"), not(empty()));
    Assert.assertEquals("bearer", params.getFirst("token_type"));
    Assert.assertThat(Integer.parseInt(params.getFirst("expires_in")), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode(params.getFirst("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read", "uaa.user"));

    validateToken("access_token", params.toSingleValueMap(), scopes, aud);
    validateToken("id_token", params.toSingleValueMap(), openid, new String[] { "cf" });
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.OpenIdTokenGrantsIT.java

@Test
public void testPasswordGrant() throws Exception {
    String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("cf:").getBytes()));

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.set("Authorization", basicDigestHeaderValue);

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "cf");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("grant_type", "password");
    postBody.add("username", user.getUserName());
    postBody.add("password", secret);

    ResponseEntity<Map> responseEntity = restOperations.exchange(loginUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), Map.class);

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

    Map<String, Object> params = responseEntity.getBody();

    Assert.assertTrue(params.get("jti") != null);
    Assert.assertEquals("bearer", params.get("token_type"));
    Assert.assertThat((Integer) params.get("expires_in"), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode((String) params.get("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read", "uaa.user"));

    validateToken("access_token", params, scopes, aud);
    validateToken("id_token", params, openid, new String[] { "cf" });
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.OpenIdTokenGrantsIT.java

private void doOpenIdHybridFlowIdTokenAndCode(Set<String> responseTypes, String responseTypeMatcher)
        throws Exception {

    HttpHeaders headers = new HttpHeaders();
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    StringBuilder responseType = new StringBuilder();
    Iterator<String> rTypes = responseTypes.iterator();
    while (rTypes.hasNext()) {
        String type = rTypes.next();
        responseType.append(type);//from  w w w.j a  v  a2  s  .  c o  m
        if (rTypes.hasNext()) {
            responseType.append(" ");
        }
    }
    String state = new RandomValueStringGenerator().generate();
    String clientId = "app";
    String clientSecret = "appclientsecret";
    String redirectUri = "http://localhost:8080/app/";
    String uri = loginUrl + "/oauth/authorize?response_type={response_type}&"
            + "state={state}&client_id={client_id}&redirect_uri={redirect_uri}";

    ResponseEntity<Void> result = restOperations.exchange(uri, HttpMethod.GET, new HttpEntity<>(null, headers),
            Void.class, responseType, state, clientId, redirectUri);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");

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

    ResponseEntity<String> response = restOperations.exchange(location, HttpMethod.GET,
            new HttpEntity<>(null, headers), String.class);
    // 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());

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

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
    formData.add("username", user.getUserName());
    formData.add("password", secret);
    formData.add(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, csrf);

    // Should be redirected to the original URL, but now authenticated
    result = restOperations.exchange(loginUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(formData, headers), Void.class);
    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);
        }
    }

    location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    response = restOperations.exchange(location, HttpMethod.GET, new HttpEntity<>(null, headers), String.class);
    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("You can change your approval of permissions"));

        formData.clear();
        formData.add(USER_OAUTH_APPROVAL, "true");
        formData.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody()));
        result = restOperations.exchange(loginUrl + "/oauth/authorize", HttpMethod.POST,
                new HttpEntity<>(formData, headers), Void.class);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    } else {
        // Token cached so no need for second approval
        assertEquals(HttpStatus.FOUND, response.getStatusCode());
        location = UriUtils.decode(response.getHeaders().getLocation().toString(), "UTF-8");
    }
    assertTrue("Wrong location: " + location, location.matches(redirectUri + responseTypeMatcher.toString()));

    formData.clear();
    formData.add("client_id", clientId);
    formData.add("redirect_uri", redirectUri);
    formData.add("grant_type", "authorization_code");
    formData.add("code", location.split("code=")[1].split("&")[0]);
    HttpHeaders tokenHeaders = new HttpHeaders();
    String basicDigestHeaderValue = "Basic "
            + new String(Base64.encodeBase64((clientId + ":" + clientSecret).getBytes()));
    tokenHeaders.set("Authorization", basicDigestHeaderValue);

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> tokenResponse = restOperations.exchange(loginUrl + "/oauth/token", HttpMethod.POST,
            new HttpEntity<>(formData, tokenHeaders), Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> body = tokenResponse.getBody();
    Jwt token = JwtHelper.decode(body.get("access_token"));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"aud\""));
    assertTrue("Wrong claims: " + token.getClaims(), token.getClaims().contains("\"user_id\""));
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginWithLocalIdpIT.java

@Test
public void testInvalidSaml2Bearer() throws Exception {
    SamlIdentityProviderDefinition idpDef = createLocalSamlIdpDefinition(IDP_ENTITY_ID, "uaa");
    @SuppressWarnings("unchecked")
    IdentityProvider<SamlIdentityProviderDefinition> provider = IntegrationTestUtils.createIdentityProvider(
            "Local SAML IdP", IDP_ENTITY_ID, true, this.baseUrl, this.serverRunning, idpDef);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("grant_type", "urn:ietf:params:oauth:grant-type:saml2-bearer");
    postBody.add("client_id", "oauth_showcase_saml2_bearer");
    postBody.add("client_secret", "secret");
    postBody.add("assertion",
            "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c2FtbDI6QXNzZXJ0aW9uIHhtbG5zOnNhbWwyPS"
                    + "J1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXNzZXJ0aW9uIiBJRD0iXzBkNzhhYTdhLTY4MzctNDUyNi1iNTk4"
                    + "LTliZGE0MTI5NTE0YiIgSXNzdWVJbnN0YW50PSIyMDE2LTExLTIyVDIxOjU3OjMwLjI2NVoiIFZlcnNpb249IjIuMC"
                    + "IgeG1sbnM6eHM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hIj48c2FtbDI6SXNzdWVyPmNsb3VkZm91"
                    + "bmRyeS1zYW1sLWxvZ2luPC9zYW1sMjpJc3N1ZXI-PHNhbWwyOlN1YmplY3Q-PHNhbWwyOk5hbWVJRCBGb3JtYXQ9In"
                    + "VybjpvYXNpczpuYW1lczp0YzpTQU1MOjEuMTpuYW1laWQtZm9ybWF0OnVuc3BlY2lmaWVkIj5Vbml0VGVzdFRlc3RV"
                    + "c2VyPC9zYW1sMjpOYW1lSUQ-PHNhbWwyOlN1YmplY3RDb25maXJtYXRpb24gTWV0aG9kPSJ1cm46b2FzaXM6bmFtZX"
                    + "M6dGM6U0FNTDoyLjA6Y206YmVhcmVyIj48c2FtbDI6U3ViamVjdENvbmZpcm1hdGlvbkRhdGEgTm90T25PckFmdGVy"
                    + "PSIyMDE3LTExLTIyVDIyOjAyOjMwLjI5NloiIFJlY2lwaWVudD0iaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYX"
                    + "V0aC90b2tlbiIvPjwvc2FtbDI6U3ViamVjdENvbmZpcm1hdGlvbj48L3NhbWwyOlN1YmplY3Q-PHNhbWwyOkNvbmRp"
                    + "dGlvbnMgTm90QmVmb3JlPSIyMDE2LTExLTIyVDIxOjU3OjMwLjI2NVoiIE5vdE9uT3JBZnRlcj0iMjAxNy0xMS0yMl"
                    + "QyMjowMjozMC4yOTZaIj48c2FtbDI6QXVkaWVuY2VSZXN0cmljdGlvbj48c2FtbDI6QXVkaWVuY2U-aHR0cDovL2xv"
                    + "Y2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbjwvc2FtbDI6QXVkaWVuY2U-PC9zYW1sMjpBdWRpZW5jZVJlc3RyaW"
                    + "N0aW9uPjwvc2FtbDI6Q29uZGl0aW9ucz48c2FtbDI6QXR0cmlidXRlU3RhdGVtZW50PjxzYW1sMjpBdHRyaWJ1dGUg"
                    + "TmFtZT0iR3JvdXBzIj48c2FtbDI6QXR0cmlidXRlVmFsdWUgeG1sbnM6eHNpPSJodHRwOi8vd3d3LnczLm9yZy8yMD"
                    + "AxL1hNTFNjaGVtYS1pbnN0YW5jZSIgeHNpOnR5cGU9InhzOnN0cmluZyI-Y2xpZW50LndyaXRlPC9zYW1sMjpBdHRy"
                    + "aWJ1dGVWYWx1ZT48c2FtbDI6QXR0cmlidXRlVmFsdWUgeG1sbnM6eHNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1"
                    + "hNTFNjaGVtYS1pbnN0YW5jZSIgeHNpOnR5cGU9InhzOnN0cmluZyI-Y2xpZW50LnJlYWQ8L3NhbWwyOkF0dHJpYnV0"
                    + "ZVZhbHVlPjwvc2FtbDI6QXR0cmlidXRlPjwvc2FtbDI6QXR0cmlidXRlU3RhdGVtZW50PjxzYW1sMjpBdXRoblN0YX"
                    + "RlbWVudCBBdXRobkluc3RhbnQ9IjIwMTYtMTEtMjJUMjI6MDI6MzAuMjk5WiIgU2Vzc2lvbk5vdE9uT3JBZnRlcj0i"
                    + "MjAxNi0xMi0yMlQyMjowMjozMC4yOTlaIj48c2FtbDI6QXV0aG5Db250ZXh0PjxzYW1sMjpBdXRobkNvbnRleHRDbG"
                    + "Fzc1JlZj51cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YWM6Y2xhc3NlczpQYXNzd29yZDwvc2FtbDI6QXV0aG5D"
                    + "b250ZXh0Q2xhc3NSZWY-PC9zYW1sMjpBdXRobkNvbnRleHQ-PC9zYW1sMjpBdXRoblN0YXRlbWVudD48L3NhbWwyOk"
                    + "Fzc2VydGlvbj4");

    try {/* w  w w . jav  a 2  s  . co  m*/
        restOperations.exchange(baseUrl + "/oauth/token", HttpMethod.POST, new HttpEntity<>(postBody, headers),
                Void.class);
    } catch (HttpClientErrorException he) {
        Assert.assertEquals(HttpStatus.UNAUTHORIZED, he.getStatusCode());
    }

    provider.setActive(false);
    IntegrationTestUtils.updateIdentityProvider(this.baseUrl, this.serverRunning, provider);
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginWithLocalIdpIT.java

@Test
public void testValidSaml2Bearer() throws Exception {
    SamlIdentityProviderDefinition idpDef = createLocalSamlIdpDefinition(IDP_ENTITY_ID, "uaa");
    @SuppressWarnings("unchecked")
    IdentityProvider<SamlIdentityProviderDefinition> provider = IntegrationTestUtils.createIdentityProvider(
            "Local SAML IdP", IDP_ENTITY_ID, true, this.baseUrl, this.serverRunning, idpDef);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("grant_type", "urn:ietf:params:oauth:grant-type:saml2-bearer");
    postBody.add("client_id", "oauth_showcase_saml2_bearer");
    postBody.add("client_secret", "secret");
    postBody.add("assertion", samlTestUtils.mockAssertionEncoded(IDP_ENTITY_ID,
            "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified", "Saml2BearerIntegrationUser",
            "http://localhost:8080/uaa/oauth/token/alias/cloudfoundry-saml-login", "cloudfoundry-saml-login"));

    ResponseEntity<CompositeAccessToken> token = restOperations.exchange(
            baseUrl + "/oauth/token/alias/cloudfoundry-saml-login", HttpMethod.POST,
            new HttpEntity<>(postBody, headers), CompositeAccessToken.class);

    Assert.assertEquals(HttpStatus.OK, token.getStatusCode());
    Assert.assertTrue(token.hasBody());//  ww  w  .j a v a  2 s . c  o m
    provider.setActive(false);
    IntegrationTestUtils.updateIdentityProvider(this.baseUrl, this.serverRunning, provider);
}

From source file:org.cloudfoundry.identity.uaa.integration.ImplicitTokenGrantIntegrationTests.java

@Test
public void authzViaJsonEndpointSucceedsWithCorrectCredentials() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    String credentials = String.format("{ \"username\":\"%s\", \"password\":\"%s\" }",
            testAccounts.getUserName(), testAccounts.getPassword());

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("credentials", credentials);
    ResponseEntity<Void> result = serverRunning.postForResponse(implicitUrl(), headers, formData);

    assertNotNull(result.getHeaders().getLocation());
    assertTrue(result.getHeaders().getLocation().toString().matches(REDIRECT_URL_PATTERN));

}

From source file:org.cloudfoundry.identity.uaa.integration.ImplicitTokenGrantIntegrationTests.java

@Test
public void authzViaJsonEndpointSucceedsWithAcceptForm() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_FORM_URLENCODED));

    String credentials = String.format("{ \"username\":\"%s\", \"password\":\"%s\" }",
            testAccounts.getUserName(), testAccounts.getPassword());

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("credentials", credentials);
    ResponseEntity<Void> result = serverRunning.postForResponse(implicitUrl(), headers, formData);

    URI location = result.getHeaders().getLocation();
    assertNotNull(location);//  ww  w. java  2 s. c om
    assertTrue("Wrong location: " + location, location.toString().matches(REDIRECT_URL_PATTERN));

}

From source file:org.cloudfoundry.identity.uaa.integration.OpenIdTokenAuthorizationWithApprovalIntegrationTests.java

@Test
public void testOpenIdTokenUsingLoginClientOauthTokenEndpoint() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("client_id", "app");
    postBody.add("client_secret", "appclientsecret");
    postBody.add("redirect_uri", "https://uaa.cloudfoundry.com/redirect/cf");
    postBody.add("response_type", "token id_token");
    postBody.add("grant_type", "password");
    postBody.add("source", "login");
    postBody.add("user_id", user.getId());
    postBody.add("add_new", "false");

    ResponseEntity<Map> responseEntity = loginClient.exchange(serverRunning.getBaseUrl() + "/oauth/token",
            HttpMethod.POST, new HttpEntity<>(postBody, headers), Map.class);

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

    Map<String, Object> params = responseEntity.getBody();

    Assert.assertTrue(params.get("jti") != null);
    Assert.assertEquals("bearer", params.get("token_type"));
    Assert.assertThat((Integer) params.get("expires_in"), Matchers.greaterThan(40000));

    String[] scopes = UriUtils.decode((String) params.get("scope"), "UTF-8").split(" ");
    Assert.assertThat(Arrays.asList(scopes), containsInAnyOrder("scim.userids", "password.write",
            "cloud_controller.write", "openid", "cloud_controller.read"));
}

From source file:org.cloudfoundry.identity.uaa.integration.OpenIdTokenAuthorizationWithApprovalIntegrationTests.java

private String doOpenIdHybridFlowIdTokenAndReturnCode(Set<String> responseTypes, String responseTypeMatcher)
        throws Exception {

    HttpHeaders headers = new HttpHeaders();
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

    AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource();

    StringBuilder responseType = new StringBuilder();
    Iterator<String> rTypes = responseTypes.iterator();
    while (rTypes.hasNext()) {
        String type = rTypes.next();
        responseType.append(type);/*from   w ww . j  a va 2s  .c  o  m*/
        if (rTypes.hasNext()) {
            responseType.append(" ");
        }
    }
    String state = new RandomValueStringGenerator().generate();
    String clientId = resource.getClientId();
    String redirectUri = resource.getPreEstablishedRedirectUri();
    String clientSecret = resource.getClientSecret();
    String uri = serverRunning.getUrl("/oauth/authorize?response_type={response_type}&"
            + "state={state}&client_id={client_id}&redirect_uri={redirect_uri}");

    ResponseEntity<Void> result = serverRunning.getForResponse(uri, headers, responseType, state, clientId,
            redirectUri);
    assertEquals(HttpStatus.FOUND, result.getStatusCode());
    String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    ResponseEntity<String> response = serverRunning.getForString(location, headers);
    // should be directed to the login screen...
    assertTrue(response.getBody().contains("/login.do"));
    assertTrue(response.getBody().contains("username"));
    assertTrue(response.getBody().contains("password"));

    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("username", user.getUserName());
    formData.add("password", "secret");

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

    if (result.getHeaders().containsKey("Set-Cookie")) {
        String cookie = result.getHeaders().getFirst("Set-Cookie");
        headers.set("Cookie", cookie);
    }

    location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    response = serverRunning.getForString(location, headers);
    if (response.getStatusCode() == HttpStatus.OK) {
        // The grant access page should be returned
        assertTrue(response.getBody().contains("Application Authorization</h1>"));

        formData.clear();
        formData.add("user_oauth_approval", "true");
        result = serverRunning.postForResponse("/oauth/authorize", headers, formData);
        assertEquals(HttpStatus.FOUND, result.getStatusCode());
        location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8");
    } else {
        // Token cached so no need for second approval
        assertEquals(HttpStatus.FOUND, response.getStatusCode());
        location = UriUtils.decode(response.getHeaders().getLocation().toString(), "UTF-8");
    }
    assertTrue("Wrong location: " + location,
            location.matches(resource.getPreEstablishedRedirectUri() + responseTypeMatcher.toString()));

    String code = location.split("code=")[1].split("&")[0];
    exchangeCodeForToken(clientId, redirectUri, clientSecret, code, formData);
    return code;
}