Expand my Community achievements bar.

SOLVED

Generate Server to Server Authentication access token from java

Avatar

Level 8

Hello everyone,

I was referring to this URL for generating the access token. I was able to generate access token from Postman software

https://developer.adobe.com/developer-console/docs/guides/authentication/ServerToServerAuthenticatio...

But was failing from java code. Here is my code snippet.

Created standalone java application, just to get the access token.

Added these maven dependencies.

<dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient-osgi</artifactId>
                <version>4.5.2</version>
                <scope>provided</scope>
	</dependency>
	<dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpcore-osgi</artifactId>
                <version>4.4.5</version>
                <scope>provided</scope>
	</dependency>
try (CloseableHttpClient httpclient = HttpClients.createDefault()) {
     	   
            HttpPost httpPost = new HttpPost("https://ims-na1.adobelogin.com/ims/token/v3");
            String postBody = "{\"grant_type\":\"client_credentials\",\"client_id\":\"123456\",\"client_secret\":\"abcd-EFGHIJKL\",\"scope\":\"openid,AdobeID,additional_info.projectedProductContext\"}";
            
            StringEntity jsonInput = new StringEntity(postBody,"UTF-8");
            httpPost.setEntity(jsonInput);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
            
            HttpResponse httpResponse = httpclient.execute(httpPost);

            // Extract the response's content
            HttpEntity responseEntity = httpResponse.getEntity();
            String response = EntityUtils.toString(responseEntity);
         
            System.out.println("Response="+response);
            System.out.println("status code="+httpResponse.getStatusLine().getStatusCode());
            
}catch(Exception e) {
        	
        	System.out.println("error occurred. "+ e.getMessage());
}

Note: Added proper client  id, secret. Still not getting proper response.

1 Accepted Solution

Avatar

Correct answer by
Level 10

@Mahesh_Gunaje Try below code once as it is working in my local:


Encoding client id and secret is main here

String credentials = clientId + ":" + clientSecret;
        String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());



 

 

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
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;

public class ServerToServerAuth {

    public static void main(String[] args) throws IOException {
        // Configuration
        String tokenEndpoint = "https://example.com/oauth/token";
        String clientId = "your_client_id";
        String clientSecret = "your_client_secret";

        // Request parameters
        String grantType = "client_credentials";

        // Constructing the credentials string
        String credentials = clientId + ":" + clientSecret;
        String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());

        // Constructing the request body
        String requestBody = "grant_type=" + URLEncoder.encode(grantType, StandardCharsets.UTF_8)
                + "&scope=" + URLEncoder.encode("your_scope", StandardCharsets.UTF_8); // Add scope if required

        // Creating the HTTP client
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // Creating the HTTP POST request
            HttpPost httpPost = new HttpPost(tokenEndpoint);

            // Adding headers
            httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedCredentials);
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            // Adding the request body
            httpPost.setEntity(new StringEntity(requestBody));

            // Executing the request
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // Processing the response
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String jsonResponse = EntityUtils.toString(entity);
                    System.out.println("Response: " + jsonResponse);
                }
            }
        }
    }
}

 

 

 

 

View solution in original post

3 Replies

Avatar

Correct answer by
Level 10

@Mahesh_Gunaje Try below code once as it is working in my local:


Encoding client id and secret is main here

String credentials = clientId + ":" + clientSecret;
        String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());



 

 

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
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;

public class ServerToServerAuth {

    public static void main(String[] args) throws IOException {
        // Configuration
        String tokenEndpoint = "https://example.com/oauth/token";
        String clientId = "your_client_id";
        String clientSecret = "your_client_secret";

        // Request parameters
        String grantType = "client_credentials";

        // Constructing the credentials string
        String credentials = clientId + ":" + clientSecret;
        String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());

        // Constructing the request body
        String requestBody = "grant_type=" + URLEncoder.encode(grantType, StandardCharsets.UTF_8)
                + "&scope=" + URLEncoder.encode("your_scope", StandardCharsets.UTF_8); // Add scope if required

        // Creating the HTTP client
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // Creating the HTTP POST request
            HttpPost httpPost = new HttpPost(tokenEndpoint);

            // Adding headers
            httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedCredentials);
            httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            // Adding the request body
            httpPost.setEntity(new StringEntity(requestBody));

            // Executing the request
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // Processing the response
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String jsonResponse = EntityUtils.toString(entity);
                    System.out.println("Response: " + jsonResponse);
                }
            }
        }
    }
}

 

 

 

 

Avatar

Level 8

Thanks @Imran__Khan  for the quick response.

Solution works like a charm   

One more query. Since, the topic is: Server to Server Authentication. So, Access token is not specific to any end user. So, end user is not required to authenticate by providing his/her Adobe credentials. So, Ideally I need to keep this access token in server. Then, for each end user request, use the same access token till it expires. How I can achieve this feature?

- Thanks

Avatar

Level 10

@Mahesh_Gunaje According to current JSON response, You will be getting only access token. you need to make one more call to get new access token once previous access token is expired.

Save this access token somewhere in AEM crx/de and create service user having very specific access to fetch access and refresh token from crx/de node. Replace tokens every time you get new one. 

 

Please try to open a new ticket for every new query as it will also help others to get specific answer given as part of query.
cc @kautuk_sahni