Example usage for org.springframework.http HttpStatus FOUND

List of usage examples for org.springframework.http HttpStatus FOUND

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus FOUND.

Prototype

HttpStatus FOUND

To view the source code for org.springframework.http HttpStatus FOUND.

Click Source Link

Document

302 Found .

Usage

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

public ResponseEntity<Void> postForRedirect(String path, HttpHeaders headers,
        MultiValueMap<String, String> params) {
    ResponseEntity<Void> exchange = postForResponse(path, headers, params);

    if (exchange.getStatusCode() != HttpStatus.FOUND) {
        throw new IllegalStateException(
                "Expected 302 but server returned status code " + exchange.getStatusCode());
    }//from  w ww. java2s.co  m

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

    String location = exchange.getHeaders().getLocation().toString();

    return client.exchange(location, HttpMethod.GET, new HttpEntity<Void>(null, headers), Void.class);
}

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  v a2 s . c om
    // TODO: should be able to handle just TEXT_HTML
    headers.setAccept(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

private View getAuthorizationCodeResponse(AuthorizationRequest authorizationRequest, Authentication authUser) {
    try {//from   w  w w .  ja v a2 s.c  om
        return new RedirectView(
                getSuccessfulRedirect(authorizationRequest, generateCode(authorizationRequest, authUser)),
                false, false, //so that we send absolute URLs always
                false) {
            @Override
            protected HttpStatus getHttp11StatusCode(HttpServletRequest request, HttpServletResponse response,
                    String targetUrl) {
                return HttpStatus.FOUND; //Override code, defaults to 303
            }
        };
    } catch (OAuth2Exception e) {
        return new RedirectView(getUnsuccessfulRedirect(authorizationRequest, e, false), false, true, false);
    }
}

From source file:org.cloudfoundry.identity.uaa.ServerRunning.java

public ResponseEntity<Void> postForRedirect(String path, HttpHeaders headers,
        MultiValueMap<String, String> params) {
    ResponseEntity<Void> exchange = postForResponse(path, headers, params);

    if (exchange.getStatusCode() != HttpStatus.FOUND) {
        throw new IllegalStateException(
                "Expected 302 but server returned status code " + exchange.getStatusCode());
    }/*from   ww w  .  ja v a 2s . c  o  m*/

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

    String location = exchange.getHeaders().getLocation().toString();

    return client.exchange(location, HttpMethod.GET, new HttpEntity<Void>(null, headers), Void.class);
}

From source file:org.eclipse.cft.server.core.internal.ssh.SshClientSupport.java

public String getSshCode() {
    try {//from ww w . j a  va2s.co  m
        URIBuilder builder = new URIBuilder(authorizationUrl + "/oauth/authorize"); //$NON-NLS-1$

        builder.addParameter("response_type" //$NON-NLS-1$
                , "code"); //$NON-NLS-1$
        builder.addParameter("grant_type", //$NON-NLS-1$
                "authorization_code"); //$NON-NLS-1$
        builder.addParameter("client_id", sshClientId); //$NON-NLS-1$

        URI url = new URI(builder.toString());

        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        HttpStatus statusCode = response.getStatusCode();
        if (statusCode != HttpStatus.FOUND) {
            throw new CloudFoundryException(statusCode);
        }

        String loc = response.getHeaders().getFirst("Location"); //$NON-NLS-1$
        if (loc == null) {
            throw new CloudOperationException("No 'Location' header in redirect response"); //$NON-NLS-1$
        }
        List<NameValuePair> qparams = URLEncodedUtils.parse(new URI(loc), "utf8"); //$NON-NLS-1$
        for (NameValuePair pair : qparams) {
            String name = pair.getName();
            if (name.equals("code")) { //$NON-NLS-1$
                return pair.getValue();
            }
        }
        throw new CloudOperationException("No 'code' param in redirect Location: " + loc); //$NON-NLS-1$
    } catch (URISyntaxException e) {
        throw new CloudOperationException(e);
    }
}

From source file:org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationEntryPointTest.java

@Test
public void testCommenceWithRedirect() throws Exception {
    configureBrowserRequest();/*from   w w  w  . jav  a2 s  .co m*/
    authenticationEntryPoint.commence(request, response, null);
    assertEquals(HttpStatus.FOUND.value(), response.getStatus());
    assertEquals(KeycloakAuthenticationEntryPoint.DEFAULT_LOGIN_URI, response.getHeader("Location"));
}

From source file:org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationEntryPointTest.java

@Test
public void testCommenceWithRedirectNotRootContext() throws Exception {
    configureBrowserRequest();//  ww  w. j  a v  a  2s  .  com
    String contextPath = "/foo";
    request.setContextPath(contextPath);
    authenticationEntryPoint.commence(request, response, null);
    assertEquals(HttpStatus.FOUND.value(), response.getStatus());
    assertEquals(contextPath + KeycloakAuthenticationEntryPoint.DEFAULT_LOGIN_URI,
            response.getHeader("Location"));
}

From source file:org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationEntryPointTest.java

@Test
public void testCommenceWithUnauthorizedWithAccept() throws Exception {
    request.addHeader(HttpHeaders.ACCEPT, "application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    authenticationEntryPoint.commence(request, response, null);
    assertEquals(HttpStatus.FOUND.value(), response.getStatus());
    assertNull(response.getHeader(HttpHeaders.WWW_AUTHENTICATE));
}

From source file:org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationEntryPointTest.java

@Test
public void testSetLoginUri() throws Exception {
    configureBrowserRequest();/* ww w  .  ja v  a 2 s  .c  om*/
    final String logoutUri = "/foo";
    authenticationEntryPoint.setLoginUri(logoutUri);
    authenticationEntryPoint.commence(request, response, null);
    assertEquals(HttpStatus.FOUND.value(), response.getStatus());
    assertEquals(logoutUri, response.getHeader("Location"));
}

From source file:org.project.openbaton.nubomedia.paas.core.openshift.AuthenticationManager.java

public String authenticate(String baseURL, String username, String password) throws UnauthorizedException {

    String res = "";

    String authBase = username + ":" + password;
    String authHeader = "Basic " + Base64.encodeBase64String(authBase.getBytes());
    logger.debug("Auth header " + authHeader);

    String url = baseURL + suffix;

    HttpHeaders authHeaders = new HttpHeaders();
    authHeaders.add("Authorization", authHeader);
    authHeaders.add("X-CSRF-Token", "1");

    UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
            .queryParam("client_id", "openshift-challenging-client").queryParam("response_type", "token");

    HttpEntity<String> authEntity = new HttpEntity<>(authHeaders);
    ResponseEntity<String> response = null;
    try {/*from w  w w  .  jav  a2 s.  c o  m*/
        response = template.exchange(builder.build().encode().toUriString(), HttpMethod.GET, authEntity,
                String.class);
    } catch (ResourceAccessException e) {
        return "PaaS Missing";
    } catch (HttpClientErrorException e) {
        throw new UnauthorizedException("Username: " + username + " password: " + password + " are invalid");
    }

    logger.debug("Response " + response.toString());

    if (response.getStatusCode().equals(HttpStatus.FOUND)) {

        URI location = response.getHeaders().getLocation();
        logger.debug("Location " + location);
        res = this.getToken(location.toString());

    } else if (response.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {

        throw new UnauthorizedException("Username: " + username + " password: " + password + " are invalid");
    }

    return res;
}