Forum Discussion

jrahman's avatar
6 months ago

How to retrieve oauth2.0 access token for grant type Client Credentials in Groovy

I am using ReadyAPI (version 3.48) and able to manually retrieve the OAuth2.0 Access Token for grant type Client Credentials from this GUI.


How can I make this Access Token retrieval automated by Groovy script so that I could use that token and assign it to a property variable and use in a subsequent REST Request



I tried this Groovy script but getting error: (java.lang.NoClassDefFoundError: org/apache/ivy/util/MessageLogger)


@Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1')


def clientId = 'df34a176-4d83-4ebf-82fd-ac6efba39e6a'
def clientSecret = 'Yf.vZQuX__l4r2x75E_iqfJl_icH6Nr6.7'
def tokenUrl = ''

// First, we obtain an access token using the client credentials grant
def http = new HTTPBuilder(tokenUrl)
http.request(Method.POST, ContentType.URLENC) { req ->
body = [
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret
response.success = { resp, reader ->
// Extract the access token from the response
def accessToken =
// Now we can use the access token to make API requests

// Finally, we can use the access token to make API requests
def makeApiRequest(accessToken) {
def http = new HTTPBuilder('')
http.request(Method.GET, ContentType.JSON) { req ->
headers['Authorization'] = "Bearer $accessToken"
response.success = { resp, reader ->
// Handle the API response

1 Reply

  • arasi_m's avatar
    Occasional Contributor

    Hi, I am using the following code to set the token automatically. You can set it as a test suite property variable and try it out.


    // Get a project
    def project = ModelSupport.getModelItemProject(context.getModelItem());

    // Get the needed authorization profile
    def authProfile = project.getAuthRepository().getEntry("YOUR AUTHORIZATION PROFILE NAME");

    //Create a facade object
    def tokenType = TokenType.ACCESS;
    def oAuthFacade = new OltuOAuth2AzureClientFacade(tokenType);

    // Request an access token in headless mode and assign it to the authorization profile we got earlier
    oAuthFacade.requestAccessToken(authProfile, true, true);

    // Access token retrieval may take time, so we need to pause the execution for 3 seconds to finish it.

    // Posts a new token to the script log"Set new token: " + authProfile.getAccessToken());