List of usage examples for org.springframework.http HttpStatus FOUND
HttpStatus FOUND
To view the source code for org.springframework.http HttpStatus FOUND.
Click Source Link
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 w w w. j av a 2s . c om 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
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 ww . j a v a2 s . c om*/ 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.ImplicitTokenGrantIntegrationTests.java
@Test public void authzWithIntermediateFormLoginSucceeds() throws Exception { BasicCookieStore cookies = new BasicCookieStore(); ResponseEntity<Void> result = serverRunning.getForResponse(implicitUrl(), getHeaders(cookies)); 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")) { int nameLength = cookie.indexOf('='); cookies.addCookie(/*from www. j a v a 2 s .c o m*/ new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } ResponseEntity<String> response = serverRunning.getForString(location, getHeaders(cookies)); if (response.getHeaders().containsKey("Set-Cookie")) { for (String cookie : response.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie( new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } // should be directed to the login screen... assertTrue(response.getBody().contains("/login.do")); assertTrue(response.getBody().contains("username")); assertTrue(response.getBody().contains("password")); location = "/login.do"; MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", testAccounts.getUserName()); formData.add("password", testAccounts.getPassword()); formData.add(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody())); result = serverRunning.postForRedirect(location, getHeaders(cookies), formData); // System.err.println(result.getStatusCode()); // System.err.println(result.getHeaders()); assertNotNull(result.getHeaders().getLocation()); assertTrue(result.getHeaders().getLocation().toString().matches(REDIRECT_URL_PATTERN)); }
From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java
@Test @OAuth2ContextConfiguration(LoginClient.class) public void testLoginServerCanAuthenticateUserForCf() throws Exception { ImplicitResourceDetails resource = testAccounts.getDefaultImplicitResource(); params.set("client_id", resource.getClientId()); params.set("username", userForLoginServer.getUserName()); params.set(OriginKeys.ORIGIN, userForLoginServer.getOrigin()); params.set(UaaAuthenticationDetails.ADD_NEW, "false"); String redirect = resource.getPreEstablishedRedirectUri(); if (redirect != null) { params.set("redirect_uri", redirect); }//from w w w. j av a2 s .c om @SuppressWarnings("rawtypes") ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAuthorizationUri(), params, headers); assertEquals(HttpStatus.FOUND, response.getStatusCode()); String results = response.getHeaders().getLocation().toString(); assertNotNull("There should be scopes: " + results, results.contains("#access_token")); }
From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java
@Test @OAuth2ContextConfiguration(LoginClient.class) public void testWrongUsernameIsErrorAddNewEnabled() throws Exception { ((RestTemplate) serverRunning.getRestTemplate()) .setRequestFactory(new HttpComponentsClientHttpRequestFactory()); ImplicitResourceDetails resource = testAccounts.getDefaultImplicitResource(); params.set("client_id", resource.getClientId()); params.set("username", "bogus1"); params.set(UaaAuthenticationDetails.ADD_NEW, "true"); String redirect = resource.getPreEstablishedRedirectUri(); if (redirect != null) { params.set("redirect_uri", redirect); }// ww w. j a va2 s . co m @SuppressWarnings("rawtypes") ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAuthorizationUri(), params, headers); // add_new:true user accounts are automatically provisioned. assertEquals(HttpStatus.FOUND, response.getStatusCode()); String results = response.getHeaders().getLocation().getFragment(); assertTrue("There should be an access token: " + results, results.contains("access_token")); }
From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java
@Test @OAuth2ContextConfiguration(LoginClient.class) public void testAddNewUserWithWrongEmailFormat() throws Exception { ((RestTemplate) serverRunning.getRestTemplate()) .setRequestFactory(new HttpComponentsClientHttpRequestFactory()); params.set("client_id", testAccounts.getDefaultImplicitResource().getClientId()); params.set("source", "login"); params.set("username", "newuser"); params.remove("given_name"); params.remove("family_name"); params.set("email", "noAtSign"); params.set(UaaAuthenticationDetails.ADD_NEW, "true"); @SuppressWarnings("rawtypes") ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAuthorizationUri(), params, headers);//from w w w .j a v a 2 s . co m assertNotNull(response); assertNotEquals(HttpStatus.INTERNAL_SERVER_ERROR, response.getStatusCode()); assertEquals(HttpStatus.FOUND, response.getStatusCode()); @SuppressWarnings("unchecked") Map<String, String> results = response.getBody(); if (results != null) { assertFalse("There should not be an error: " + results, results.containsKey("error")); } }
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);/* w ww . j ava 2 s . 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; }
From source file:org.cloudfoundry.identity.uaa.integration.OpenIdTokenAuthorizationWithApprovalIntegrationTests.java
private void doOpenIdHybridFlowForLoginClient(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.APPLICATION_JSON, 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);// www .j a v a2 s .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}&client_secret={clientSecret}&redirect_uri={redirect_uri}&source=login&user_id={userId}&add_new=false"); HttpEntity<Void> request = new HttpEntity<>(null, headers); ResponseEntity<Map> result = loginClient.exchange(serverRunning.getUrl(uri), HttpMethod.POST, request, Map.class, responseType, state, clientId, clientSecret, redirectUri, user.getId()); assertEquals(HttpStatus.FOUND, result.getStatusCode()); String location = UriUtils.decode(result.getHeaders().getLocation().toString(), "UTF-8"); assertTrue("Wrong location: " + location, location.matches(resource.getPreEstablishedRedirectUri() + responseTypeMatcher.toString())); }
From source file:org.cloudfoundry.identity.uaa.integration.RefreshTokenSupportIntegrationTests.java
@Test public void testTokenRefreshedCorrectFlow() throws Exception { BasicCookieStore cookies = new BasicCookieStore(); AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource(); URI uri = serverRunning.buildUri("/oauth/authorize").queryParam("response_type", "code") .queryParam("state", "mystateid").queryParam("client_id", resource.getClientId()) .queryParam("redirect_uri", resource.getPreEstablishedRedirectUri()).build(); ResponseEntity<Void> result = serverRunning.getForResponse(uri.toString(), getHeaders(cookies)); 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")) { int nameLength = cookie.indexOf('='); cookies.addCookie(/* www. ja v a 2 s . co m*/ new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } ResponseEntity<String> response = serverRunning.getForString(location, getHeaders(cookies)); if (response.getHeaders().containsKey("Set-Cookie")) { for (String cookie : response.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie( new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } // 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", testAccounts.getUserName()); formData.add("password", testAccounts.getPassword()); formData.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody())); // Should be redirected to the original URL, but now authenticated result = serverRunning.postForResponse("/login.do", getHeaders(cookies), formData); cookies.clear(); if (result.getHeaders().containsKey("Set-Cookie")) { for (String cookie : result.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie( new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } assertEquals(HttpStatus.FOUND, result.getStatusCode()); response = serverRunning.getForString(result.getHeaders().getLocation().toString(), getHeaders(cookies)); if (response.getHeaders().containsKey("Set-Cookie")) { for (String cookie : response.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie( new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } 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", getHeaders(cookies), 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(); } assertTrue("Wrong location: " + location, location.matches(resource.getPreEstablishedRedirectUri() + ".*code=.+")); formData.clear(); formData.add("client_id", resource.getClientId()); formData.add("redirect_uri", resource.getPreEstablishedRedirectUri()); formData.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE); formData.add("code", location.split("code=")[1].split("&")[0]); HttpHeaders tokenHeaders = new HttpHeaders(); tokenHeaders.set("Authorization", testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret())); tokenHeaders.set("Cache-Control", "no-store"); @SuppressWarnings("rawtypes") ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); @SuppressWarnings("unchecked") OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(tokenResponse.getBody()); // get the refresh token formData = new LinkedMultiValueMap<String, String>(); formData.add("grant_type", "refresh_token"); formData.add("refresh_token", accessToken.getRefreshToken().getValue()); tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); assertEquals("no-store", tokenResponse.getHeaders().getFirst("Cache-Control")); @SuppressWarnings("unchecked") OAuth2AccessToken newAccessToken = DefaultOAuth2AccessToken.valueOf(tokenResponse.getBody()); try { JwtHelper.decode(newAccessToken.getValue()); } catch (IllegalArgumentException e) { fail("Refreshed token was not a JWT"); } assertFalse("New access token should be different to the old one.", newAccessToken.getValue().equals(accessToken.getValue())); }
From source file:org.cloudfoundry.identity.uaa.integration.ScimGroupEndpointsIntegrationTests.java
private OAuth2AccessToken getAccessToken(String clientId, String clientSecret, String username, String password) throws URISyntaxException { HttpHeaders headers = new HttpHeaders(); headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL)); URI uri = serverRunning.buildUri("/oauth/authorize").queryParam("response_type", "code") .queryParam("state", "mystateid").queryParam("client_id", clientId) .queryParam("redirect_uri", "http://anywhere.com").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")) { headers.add("Cookie", cookie); }// w ww. j ava 2s . c om } 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")); if (response.getHeaders().containsKey("Set-Cookie")) { String cookie = response.getHeaders().getFirst("Set-Cookie"); headers.add("Cookie", cookie); } MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", username); formData.add("password", password); formData.add(CookieBasedCsrfTokenRepository.DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody())); // 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( new URI(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(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody())); formData.add(USER_OAUTH_APPROVAL, "true"); formData.add("scope.0", "scope." + CFID); 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(); } assertTrue("Wrong location: " + location, location.matches("http://anywhere.com" + ".*code=.+")); formData.clear(); formData.add("client_id", clientId); formData.add("redirect_uri", "http://anywhere.com"); formData.add("grant_type", "authorization_code"); 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()); return accessToken; }