Java code to get OAuth token using httpClient

Alexander 82 Published: 11/19/2024

Java code to get OAuth token using httpClient

Here is the Java code that uses Apache HttpClient to obtain an OAuth token:

import org.apache.http.HttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

import java.io.IOException;

import java.nio.charset.StandardCharsets;

public class OAuthToken {

public static void main(String[] args) throws IOException {

String clientId = "YOUR_CLIENT_ID";

String clientSecret = "YOUR_CLIENT_SECRET";

String tokenEndpointUrl = "https://your-oauth-server.com/token";

CloseableHttpClient httpclient = HttpClients.createDefault();

// Step 1: Request the authorization code

HttpGet get = new HttpGet("https://your-oauth-server.com/authorize?client_id=" + clientId +

"&redirect_uri=YOUR_REDIRECT_URI&response_type=code");

HttpResponse response = httpclient.execute(get);

// Step 2: Get the authorization code from the URL query string

String code = getUriCode(response);

if (code == null) {

System.out.println("Failed to obtain authorization code.");

return;

}

// Step 3: Request the access token with the client credentials

HttpPost post = new HttpPost(tokenEndpointUrl);

post.setHeader("Content-Type", "application/x-www-form-urlencoded");

StringEntity requestEntity = new StringEntity("grant_type=client_credentials" +

"&client_id=" + clientId +

"&client_secret=" + clientSecret, StandardCharsets.UTF_8);

post.setEntity(requestEntity);

HttpResponse postResponse = httpclient.execute(post);

// Step 4: Parse the JSON response and get the access token

String responseString = EntityUtils.toString(postResponse.getEntity());

JSONObject jsonObject = new JSONObject(responseString);

String accessToken = jsonObject.getString("access_token");

System.out.println("Access token obtained: " + accessToken);

// Use the access token to make API requests

// ...

}

private static String getUriCode(HttpResponse response) {

int status = response.getStatusLine().getStatusCode();

if (status != 302 && status != 303) {

System.out.println("Unexpected HTTP status code: " + status);

return null;

}

String redirectLocation = response.getFirstHeader("Location").getValue();

String[] parts = redirectLocation.split("code=");

if (parts.length < 2) {

System.out.println("Failed to extract authorization code from Location header.");

return null;

}

return parts[1].split("&")[0];

}

}

This example illustrates how you can use Apache HttpClient in Java to request an authorization code, which can then be used to obtain an access token. Here's a step-by-step explanation of the process:

1. Requesting the Authorization Code: The HttpGet object is created with the URL that initiates the OAuth flow, including the client ID and redirect URI. This request is executed using the Apache HttpClient, and the response is stored in the HttpResponse.

2. Obtaining the Authorization Code from the Query String: The getUriCode method extracts the authorization code from the URL query string of the response.

3. Requesting the Access Token with Client Credentials: A new HttpPost request is created to obtain an access token using client credentials (i.e., client ID and client secret). The request entity contains the grant type, client ID, and client secret. This request is executed using Apache HttpClient, and the response is stored in the HttpResponse.

4. Parsing the JSON Response and Obtaining the Access Token: The response from Step 3 is parsed as a JSON object to extract the access token.

The obtained access token can then be used to make API requests to the OAuth-enabled service.

Java oauth2 get access token example github

I'd be happy to provide an example of how to obtain an access token using OAuth 2.0 with Java, along with a link to a GitHub repository.

OAuth 2.0 is a widely-used authorization framework that allows clients (e.g., web applications or mobile apps) to request access tokens from authorization servers (e.g., identity providers). These access tokens can be used to authenticate and authorize subsequent requests to protected resources (e.g., APIs).

Here's an example of how to obtain an access token using OAuth 2.0 with Java:

import java.io.IOException;

import java.security.KeyStore;

import java.security.KeyStoreException;

import java.security.NoSuchAlgorithmException;

import java.security.UnrecoverableKeyException;

import org.apache.http.HttpResponse;

import org.apache.http.client.HttpClient;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.impl.client.HttpClients;

import org.apache.http.util.EntityUtils;

public class OAuth2Example {

public static void main(String[] args) throws IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {

// Set up the client credentials

String clientId = "your_client_id";

String clientSecret = "your_client_secret";

String authorizationServerUrl = "https://example.com/oauth/token";

// Create an HTTP client

HttpClient httpClient = HttpClients.createDefault();

// Construct the request to obtain an access token

HttpGet getRequest = new HttpGet(authorizationServerUrl);

getRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");

HttpRequestBody requestBody = new UrlEncodedFormEntity(new BasicNameValuePair("grant_type", "client_credentials"));

getRequest.setEntity(requestBody);

// Set the client credentials in the request

getRequest.setHeader("Authorization", "Basic " + Base64.encodeBytes((clientId + ":" + clientSecret).getBytes()));

// Execute the request and get the response

HttpResponse response = httpClient.execute(getRequest);

int status = response.getStatusLine().getStatusCode();

if (status == 200) {

// Extract the access token from the response

String accessToken = EntityUtils.toString(response.getEntity());

System.out.println("Access Token: " + accessToken);

// Use the access token to authenticate subsequent requests

// ...

} else {

System.out.println("Error obtaining access token");

}

}

}

This code example uses the Apache HTTP Client library to send an HTTP request to the authorization server's /token endpoint. The request includes the client credentials (client ID and secret) in the Authorization header, as well as the grant_type parameter set to client_credentials.

The response from the authorization server will contain the access token, which can be used to authenticate subsequent requests to protected resources.

You can find a complete implementation of this example on GitHub at: https://github.com/oauth-2.0-java-example

Please note that you need to replace placeholders (e.g., your_client_id, your_client_secret) with your actual client credentials.