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')
import groovyx.net.http.HTTPBuilder
import groovyx.net.http.Method
import groovyx.net.http.ContentType
def clientId = 'df34a176-4d83-4ebf-82fd-ac6efba39e6a'
def clientSecret = 'Yf.vZQuX__l4r2x75E_iqfJl_icH6Nr6.7'
def tokenUrl = 'https://login.microsoftonline.com/75056d76-b628-4488-82b0-80b08b52d854/oauth2/v2.0/token'
// 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 = resp.data.access_token
// Now we can use the access token to make API requests
makeApiRequest(accessToken)
}
}
// Finally, we can use the access token to make API requests
def makeApiRequest(accessToken) {
def http = new HTTPBuilder('https://inest-npd.azcpggpc.ca')
http.request(Method.GET, ContentType.JSON) { req ->
headers['Authorization'] = "Bearer $accessToken"
response.success = { resp, reader ->
// Handle the API response
println resp.data
}
}
}