Search code examples
javapostmanokta-api

GET request with redirect URL could not get 302 in JAVA but Postman works well


Here is an OKTA API call: GET {{OAuthProviderUrl}}/oauth2/v1/authorize?client_id={{clientId}}&response_type=code&response_mode=query&scope={{scopes}}&state={{state}}&sessionToken={{sessionToken}}&redirect_uri={{redirectUri}}

It can return code: 302 with a "location" header by using Postman, but... when I tried to implement the call in JAVA as:

RequestConfig config = RequestConfig.custom().setRedirectsEnabled(true).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
String location = null;
HttpResponse response;
try {
response = httpClient.execute((new HttpGet(URL));
responseCode = response.getStatusLine().getStatusCode();
} catch (Exception e) {
e.printStackTrace();
}

It always returns code: 400. Is there any different flow between postman and JAVA? Thanks.

The GET queries do not have difference from postman to Java implementation.


Solution

  • Take out the setRedirectsEnabled. It will cause the httpclient to follow the redirects rather than pass the first response back to you. The redirected-to page could be returning the 400.

    We can get more clarity on the cause of the issue by printing the response body:

    String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            System.out.println("Response body: " + responseBody);
    

    If that does not fix then it’s probably a problem with the parameters being sent from Java, resulting in the auth failing and the call returning a 400. That is pretty much the textbook definition of a 400.

    The correct way to add parameters is like this

    URI uri = new URIBuilder(“https://provider.com/oauth2/v1/authorize”)
      .addParameter("client_id", "value1")
      .addParameter("response_type", "value2")
      // etc
      .build();
    

    I find it very useful to fire httpclient calls to https://httpbin.org/get and then printing the response body as I suggest above. httpbin.org echoes what is sent allowing a comparison with postman (if you fire a call you know works to httpbin.)