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.login.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. jav a 2s. c o m*/ if (rTypes.hasNext()) { responseType.append(" "); } } String state = new RandomValueStringGenerator().generate(); String clientId = "app"; String clientSecret = "appclientsecret"; String redirectUri = "http://anywhere.com"; 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")) { String cookie = result.getHeaders().getFirst("Set-Cookie"); headers.set("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")); MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", user.getUserName()); formData.add("password", "secret"); // 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()); 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 = 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"); 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:com.projectx.mvc.servicehandler.quickregister.QuickRegisterHandler.java
@Override public MobileVerificationDetailsDTO getMobileVerificationDetailsByCustomerIdTypeAndMobile(Long customerId, Integer customerType, Integer mobileType) throws MobileVerificationDetailsNotFoundException { CustomerIdTypeMobileTypeDTO mobileDTO = new CustomerIdTypeMobileTypeDTO(customerId, customerType, mobileType);/*from w ww .j av a 2s . com*/ HttpEntity<CustomerIdTypeMobileTypeDTO> entity = new HttpEntity<CustomerIdTypeMobileTypeDTO>(mobileDTO); ResponseEntity<MobileVerificationDetailsDTO> result = restTemplate.exchange( env.getProperty("rest.host") + "/customer/quickregister/getMobileVerificationDetails", HttpMethod.POST, entity, MobileVerificationDetailsDTO.class); if (result.getStatusCode() == HttpStatus.FOUND) return result.getBody(); else throw new MobileVerificationDetailsNotFoundException(); }
From source file:com.projectx.mvc.servicehandler.quickregister.QuickRegisterHandler.java
@Override public AuthenticationDetailsDTO getAuthenticationDetailsByCustomerIdType(Long customerId, Integer customerType) throws AuthenticationDetailsNotFoundException { CustomerIdTypeDTO customerIdDTO = new CustomerIdTypeDTO(customerId, customerType); HttpEntity<CustomerIdTypeDTO> entity = new HttpEntity<CustomerIdTypeDTO>(customerIdDTO); ResponseEntity<AuthenticationDetailsDTO> result = restTemplate.exchange( env.getProperty("rest.host") + "/customer/quickregister/getAuthenticationDetailsById", HttpMethod.POST, entity, AuthenticationDetailsDTO.class); if (result.getStatusCode() == HttpStatus.FOUND) return result.getBody(); else//from w w w . j av a2s. c om throw new AuthenticationDetailsNotFoundException(); }
From source file:com.muk.services.security.DefaultUaaLoginService.java
@SuppressWarnings("unchecked") @Override/* w w w. j a va2s. com*/ public Map<String, Object> loginForClient(String username, String password, String clientId, UriComponents inUrlComponents) { final Map<String, Object> responsePayload = new HashMap<String, Object>(); final HttpHeaders headers = new HttpHeaders(); headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON_UTF8)); final UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUriString(cfgService.getOauthServer()); // login for csrf final UriComponents loginUri = uriBuilder.cloneBuilder().pathSegment("login").build(); ResponseEntity<String> response = exchangeForType(loginUri.toUriString(), HttpMethod.GET, null, headers, String.class); final List<String> cookies = new ArrayList<String>(); cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE)); final MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", username); formData.add("password", password); formData.add(CSRF, getCsrf(cookies)); headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies)); headers.add(HttpHeaders.REFERER, loginUri.toUriString()); // login.do response = exchangeForType(uriBuilder.cloneBuilder().pathSegment("login.do").build().toUriString(), HttpMethod.POST, formData, headers, String.class); if (response.getStatusCode() != HttpStatus.FOUND || response.getHeaders().getFirst(HttpHeaders.LOCATION).contains("login")) { responsePayload.put("error", "bad credentials"); return responsePayload; } removeCookie(cookies, "X-Uaa-Csrf"); cookies.addAll(response.getHeaders().get(HttpHeaders.SET_COOKIE)); removeExpiredCookies(cookies); headers.remove(HttpHeaders.REFERER); headers.put(HttpHeaders.COOKIE, translateInToOutCookies(cookies)); // authorize final ResponseEntity<JsonNode> authResponse = exchangeForType( uriBuilder.cloneBuilder().pathSegment("oauth").pathSegment("authorize") .queryParam("response_type", "code").queryParam("client_id", clientId) .queryParam("redirect_uri", inUrlComponents.toUriString()).build().toUriString(), HttpMethod.GET, null, headers, JsonNode.class); if (authResponse.getStatusCode() == HttpStatus.OK) { removeCookie(cookies, "X-Uaa-Csrf"); cookies.addAll(authResponse.getHeaders().get(HttpHeaders.SET_COOKIE)); // return approval data final List<HttpCookie> parsedCookies = new ArrayList<HttpCookie>(); for (final String cookie : cookies) { parsedCookies.add(HttpCookie.parse(cookie).get(0)); } responsePayload.put(HttpHeaders.SET_COOKIE, new ArrayList<String>()); for (final HttpCookie parsedCookie : parsedCookies) { if (!parsedCookie.getName().startsWith("Saved-Account")) { parsedCookie.setPath(inUrlComponents.getPath()); ((List<String>) responsePayload.get(HttpHeaders.SET_COOKIE)) .add(httpCookieToString(parsedCookie)); } } responsePayload.put("json", authResponse.getBody()); } else { // get auth_code from Location Header responsePayload.put("code", authResponse.getHeaders().getLocation().getQuery().split("=")[1]); } return responsePayload; }
From source file:eionet.webq.web.interceptor.CdrAuthorizationInterceptorTest.java
@Test public void whenQueryForUrlThroughInterceptor_ifAuthorizationNotEmptyAndResponseCodeIsFound_AllowToProceed() throws Exception { MockHttpServletRequest request = requestWithNonEmptyAuthHeader(); when(restOperations.postForEntity(anyString(), anyObject(), any(Class.class))) .thenReturn(new ResponseEntity(HttpStatus.FOUND)); assertTrue(interceptor.preHandle(request, new MockHttpServletResponse(), null)); }
From source file:eionet.webq.web.interceptor.CdrAuthorizationInterceptorTest.java
private void assertUrlIsExtracted(MockHttpServletRequest request, String expectedValue) throws Exception { when(restOperations.postForEntity(anyString(), anyObject(), any(Class.class))) .thenReturn(new ResponseEntity(HttpStatus.FOUND)); interceptor.preHandle(request, new MockHttpServletResponse(), null); ArgumentCaptor<String> urlCaptor = ArgumentCaptor.forClass(String.class); verify(restOperations).postForEntity(urlCaptor.capture(), anyObject(), any(Class.class)); assertThat(urlCaptor.getValue(), containsString(expectedValue)); }
From source file:io.spring.initializr.web.project.MainControllerIntegrationTests.java
private void assertSpringCliRedirect(String context, String extension) throws URISyntaxException { ResponseEntity<?> entity = getRestTemplate().getForEntity(createUrl(context), ResponseEntity.class); assertEquals(HttpStatus.FOUND, entity.getStatusCode()); String expected = "https://repo.spring.io/release/org/springframework/boot/spring-boot-cli/1.1.4.RELEASE/spring-boot-cli-1.1.4.RELEASE-bin." + extension;/*w w w . j a va2 s . c o m*/ assertEquals(new URI(expected), entity.getHeaders().getLocation()); }
From source file:org.ambraproject.rhino.rest.controller.ContentRepoController.java
private static ResponseEntity<?> serveFromRemoteRepo(URI contentRepoAddress, String bucket, String key, String version) {/*w w w .j a va2s . c o m*/ URI location = URI.create(String.format("%s/objects/%s?key=%s", // TODO Use version contentRepoAddress, bucket, key)); HttpHeaders headers = new HttpHeaders(); headers.setLocation(location); return new ResponseEntity<Object>(headers, HttpStatus.FOUND); }
From source file:org.cloudfoundry.identity.uaa.integration.CheckTokenEndpointIntegrationTests.java
@Test public void testDecodeToken() { AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource(); BasicCookieStore cookies = new BasicCookieStore(); 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(//from w ww . ja v a 2s . c om 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")); String csrf = IntegrationTestUtils.extractCookieCsrf(response.getBody()); MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", testAccounts.getUserName()); formData.add("password", testAccounts.getPassword()); formData.add(DEFAULT_CSRF_COOKIE_NAME, csrf); // Should be redirected to the original URL, but now authenticated result = serverRunning.postForResponse("/login.do", getHeaders(cookies), formData); assertEquals(HttpStatus.FOUND, result.getStatusCode()); 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))); } } 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(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody())); formData.add(USER_OAUTH_APPROVAL, "true"); 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())); @SuppressWarnings("rawtypes") ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); @SuppressWarnings("unchecked") OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(tokenResponse.getBody()); HttpHeaders headers = new HttpHeaders(); formData = new LinkedMultiValueMap<String, String>(); headers.set("Authorization", testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret())); formData.add("token", accessToken.getValue()); tokenResponse = serverRunning.postForMap("/check_token", formData, headers); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); @SuppressWarnings("unchecked") Map<String, String> map = tokenResponse.getBody(); assertNotNull(map.get("iss")); assertEquals(testAccounts.getUserName(), map.get("user_name")); assertEquals(testAccounts.getEmail(), map.get("email")); // Test that Spring's default converter can create an auth from the response. Authentication auth = (new DefaultUserAuthenticationConverter()).extractAuthentication(map); }
From source file:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java
@Test public void testSimpleAutologinFlow() throws Exception { HttpHeaders headers = getAppBasicAuthHttpHeaders(); LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>(); requestBody.add("username", testAccounts.getUserName()); requestBody.add("password", testAccounts.getPassword()); //generate an autologin code with our credentials ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin", HttpMethod.POST, new HttpEntity<>(requestBody.toSingleValueMap(), headers), Map.class); String autologinCode = (String) autologinResponseEntity.getBody().get("code"); //start the authorization flow - this will issue a login event //by using the autologin code String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize") .queryParam("redirect_uri", appUrl).queryParam("response_type", "code") .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString(); //rest template that does NOT follow redirects RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory()); headers.remove("Authorization"); headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE); ResponseEntity<String> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET, new HttpEntity<>(new HashMap<String, String>(), headers), String.class); //we are now logged in. retrieve the JSESSIONID List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie"); int cookiesAdded = 0; headers = getAppBasicAuthHttpHeaders(); for (String cookie : cookies) { if (cookie.startsWith("X-Uaa-Csrf=") || cookie.startsWith("JSESSIONID=")) { headers.add("Cookie", cookie); cookiesAdded++;/*from w ww . ja v a 2 s . c o m*/ } } assertEquals(2, cookiesAdded); //if we receive a 200, then we must approve our scopes if (HttpStatus.OK == authorizeResponse.getStatusCode()) { authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize") .queryParam("user_oauth_approval", "true") .queryParam(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(authorizeResponse.getBody())) .build().toUriString(); authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST, new HttpEntity<>(new HashMap<String, String>(), headers), String.class); } //approval is complete, we receive a token code back assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode()); List<String> location = authorizeResponse.getHeaders().get("Location"); assertEquals(1, location.size()); String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5); //request a token using our code String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token").build().toUriString(); MultiValueMap<String, String> tokenParams = new LinkedMultiValueMap<>(); tokenParams.add("response_type", "token"); tokenParams.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE); tokenParams.add("code", newCode); tokenParams.add("redirect_uri", appUrl); headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(tokenParams, headers, HttpMethod.POST, new URI(tokenUrl)); ResponseEntity<Map> tokenResponse = template.exchange(requestEntity, Map.class); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); //here we must reset our state. we do that by following the logout flow. headers.clear(); BasicCookieStore cookieStore = new BasicCookieStore(); ResponseEntity<String> loginResponse = template.exchange(baseUrl + "/login", HttpMethod.GET, new HttpEntity<>(null, getHeaders(cookieStore)), String.class); setCookiesFromResponse(cookieStore, loginResponse); String csrf = IntegrationTestUtils.extractCookieCsrf(loginResponse.getBody()); requestBody.add(DEFAULT_CSRF_COOKIE_NAME, csrf); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST, new HttpEntity<>(requestBody, getHeaders(cookieStore)), String.class); cookies = loginResponse.getHeaders().get("Set-Cookie"); assertThat(cookies, hasItem(startsWith("JSESSIONID"))); assertThat(cookies, hasItem(startsWith("X-Uaa-Csrf"))); if (IdentityZoneHolder.get().getConfig().isAccountChooserEnabled()) { assertThat(cookies, hasItem(startsWith("Saved-Account-"))); } assertThat(cookies, hasItem(startsWith("Current-User"))); cookieStore.clear(); setCookiesFromResponse(cookieStore, loginResponse); headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE); ResponseEntity<String> profilePage = restOperations.exchange(baseUrl + "/profile", HttpMethod.GET, new HttpEntity<>(null, getHeaders(cookieStore)), String.class); setCookiesFromResponse(cookieStore, profilePage); String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build() .toUriString(); requestBody.clear(); requestBody.add("clientId", "app"); requestBody.add("delete", ""); requestBody.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(profilePage.getBody())); ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST, new HttpEntity<>(requestBody, getHeaders(cookieStore)), Void.class); assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode()); }