Expand my Community achievements bar.

Dive into Adobe Summit 2024! Explore curated list of AEM sessions & labs, register, connect with experts, ask questions, engage, and share insights. Don't miss the excitement.
SOLVED

Unable to generate Access Token for Oauth Service-to-Service

Avatar

Community Advisor

Hello,

 

We are using SpringFramework to generate access tokens using OAuth. But, consistently getting "Access Denied". The same credentials work for curl command. Requesting you to please suggest what might be missing

 

package com.abbott.Oauth.authentication;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.ArrayList;
import java.util.List;

public class AccessTokenGenerator {
public static void main(String[] args) {
String clientId = "client_id_cred";
String clientSecret = "client_secret_cred";
String tokenUrl = "https://ims-na1.adobelogin.com/ims/token/v2";

// Set up the OAuth2 client details
ClientCredentialsResourceDetails clientDetails = new ClientCredentialsResourceDetails();
clientDetails.setClientId(clientId);
clientDetails.setClientSecret(clientSecret);
clientDetails.setAccessTokenUri(tokenUrl);

List<String> scopes = new ArrayList<String>();
scopes.add("read_pc.dma_aem_ams");
scopes.add("openid");
scopes.add("AdobeID");
scopes.add("read_organizations");
scopes.add("additional_info.projectedProductContext");

clientDetails.setScope(scopes); // Set the desired scope

// Create an OAuth2RestTemplate using the client details
OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(clientDetails);

// Set the request headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

// Set the request body parameters
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("grant_type", "client_credentials");

// Make a request to the token endpoint to get the access token
ResponseEntity<OAuth2AccessToken> responseEntity = restTemplate.exchange(
tokenUrl,
HttpMethod.POST,
new org.springframework.http.HttpEntity<>(params, headers),
OAuth2AccessToken.class
);

if (responseEntity.getStatusCode().is2xxSuccessful()) {
OAuth2AccessToken accessToken = responseEntity.getBody();
if (accessToken != null) {
System.out.println("Access Token: " + accessToken.getValue());
System.out.println("Token Type: " + accessToken.getTokenType());
System.out.println("Expires In: " + accessToken.getExpiresIn());

// If a refresh token is provided, you can access it as well
OAuth2RefreshToken refreshToken = accessToken.getRefreshToken();
if (refreshToken != null) {
System.out.println("Refresh Token: " + refreshToken.getValue());
}
}
} else {
System.out.println("Error retrieving access token. Status code: " + responseEntity.getStatusCode());
}
}
}

 

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


Aanchal Sikka

1 Accepted Solution

Avatar

Correct answer by
Community Advisor

Sharing the code that worked and genarted access_token:

 

package com.abbott.Oauth.authentication;

import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

public class OAuth2Example {
    public static void main(String[] args) {
        // Set the base endpoint URL
        String baseUrl = "https://ims-na1.adobelogin.com/ims/token/v3";

        // Set the client credentials
        String clientId = "{CLIENT_ID}";
        String clientSecret = "{CLIENT_SECRET}";
        String scopes = "read_pc.dma_aem_ams,openid,AdobeID,read_organizations,additional_info.projectedProductContext";

        // Create the RestTemplate instance
        RestTemplate restTemplate = new RestTemplate();

        // Build the complete URL with query parameter
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("client_id", clientId);

        // Create the request headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // Create the request body parameters
        MultiValueMap<String, String> bodyParams = new LinkedMultiValueMap<>();
        bodyParams.add("client_secret", clientSecret);
        bodyParams.add("grant_type", "client_credentials");
        bodyParams.add("scope", scopes);

        // Create the request entity with headers and body
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(bodyParams, headers);

        // Send the POST request
        ResponseEntity<String> responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, requestEntity, String.class);

        // Check the response status
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            String response = responseEntity.getBody();
            // Process the response as needed
            System.out.println(response);
        } else {
            System.out.println("Error: " + responseEntity.getStatusCode());
        }
    }
}

Aanchal Sikka

View solution in original post

4 Replies

Avatar

Community Advisor

Hi @aanchal-sikka ,

 

If you are consistently getting "Access Denied" when using Spring Framework to generate access tokens using OAuth in AEM, there could be a few possible reasons for this issue. Could you please share logs?

Avatar

Community Advisor

Hello @MayurSatav 

 

Sharing the error for reference:

 

Exception in thread "main" error="access_denied", error_description="Error requesting access token."
	at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken(OAuth2AccessTokenSupport.java:149)
	at org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsAccessTokenProvider.obtainAccessToken(ClientCredentialsAccessTokenProvider.java:49)
	at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainNewAccessTokenInternal(AccessTokenProviderChain.java:155)
	at org.springframework.security.oauth2.client.token.AccessTokenProviderChain.obtainAccessToken(AccessTokenProviderChain.java:128)
	at org.springframework.security.oauth2.client.OAuth2RestTemplate.acquireAccessToken(OAuth2RestTemplate.java:241)
	at org.springframework.security.oauth2.client.OAuth2RestTemplate.getAccessToken(OAuth2RestTemplate.java:183)
	at org.springframework.security.oauth2.client.OAuth2RestTemplate.createRequest(OAuth2RestTemplate.java:115)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:778)
	at org.springframework.security.oauth2.client.OAuth2RestTemplate.doExecute(OAuth2RestTemplate.java:138)
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:717)
	at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:608)
	at com.abbott.Oauth.authentication.AccessTokenGenerator.main(AccessTokenGenerator.java:50)
Caused by: org.springframework.web.client.UnknownContentTypeException: Could not extract response: no suitable HttpMessageConverter found for response type [interface org.springframework.security.oauth2.common.OAuth2AccessToken] and content type [application/json;charset=UTF-8]
	at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:126)
	at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport$2.extractData(OAuth2AccessTokenSupport.java:138)
	at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport$2.extractData(OAuth2AccessTokenSupport.java:132)
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:784)
	at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:738)
	at org.springframework.security.oauth2.client.token.OAuth2AccessTokenSupport.retrieveToken(OAuth2AccessTokenSupport.java:141)
	... 11 more

Aanchal Sikka

Avatar

Community Advisor

Sharing the code that worked for us

 

package com.abbott.Oauth.authentication;

import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

public class OAuth2Example {
    public static void main(String[] args) {
        // Set the base endpoint URL
        String baseUrl = "https://ims-na1.adobelogin.com/ims/token/v3";

        // Set the client credentials
        String clientId = "{CLIENT_ID}";
        String clientSecret = "{CLIENT_SECRET}";
        String scopes = "read_pc.dma_aem_ams,openid,AdobeID,read_organizations,additional_info.projectedProductContext";

        // Create the RestTemplate instance
        RestTemplate restTemplate = new RestTemplate();

        // Build the complete URL with query parameter
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("client_id", clientId);

        // Create the request headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // Create the request body parameters
        MultiValueMap<String, String> bodyParams = new LinkedMultiValueMap<>();
        bodyParams.add("client_secret", clientSecret);
        bodyParams.add("grant_type", "client_credentials");
        bodyParams.add("scope", scopes);

        // Create the request entity with headers and body
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(bodyParams, headers);

        // Send the POST request
        ResponseEntity<String> responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, requestEntity, String.class);

        // Check the response status
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            String response = responseEntity.getBody();
            // Process the response as needed
            System.out.println(response);
        } else {
            System.out.println("Error: " + responseEntity.getStatusCode());
        }
    }
}

Aanchal Sikka

Avatar

Correct answer by
Community Advisor

Sharing the code that worked and genarted access_token:

 

package com.abbott.Oauth.authentication;

import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

public class OAuth2Example {
    public static void main(String[] args) {
        // Set the base endpoint URL
        String baseUrl = "https://ims-na1.adobelogin.com/ims/token/v3";

        // Set the client credentials
        String clientId = "{CLIENT_ID}";
        String clientSecret = "{CLIENT_SECRET}";
        String scopes = "read_pc.dma_aem_ams,openid,AdobeID,read_organizations,additional_info.projectedProductContext";

        // Create the RestTemplate instance
        RestTemplate restTemplate = new RestTemplate();

        // Build the complete URL with query parameter
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl)
                .queryParam("client_id", clientId);

        // Create the request headers
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        // Create the request body parameters
        MultiValueMap<String, String> bodyParams = new LinkedMultiValueMap<>();
        bodyParams.add("client_secret", clientSecret);
        bodyParams.add("grant_type", "client_credentials");
        bodyParams.add("scope", scopes);

        // Create the request entity with headers and body
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(bodyParams, headers);

        // Send the POST request
        ResponseEntity<String> responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.POST, requestEntity, String.class);

        // Check the response status
        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            String response = responseEntity.getBody();
            // Process the response as needed
            System.out.println(response);
        } else {
            System.out.println("Error: " + responseEntity.getStatusCode());
        }
    }
}

Aanchal Sikka