Satheesh-raju
2 years agoOccasional Contributor
Automating OAuth 2.0 with Client credentials grant
Hi All,
Am having an OAuth 2.0 authorization with Client Credentials Grant used in my API. I configured the authorization profile in the Auth manager as shown below and the token is expected to refresh automatically as per the settings (Shown Below).
But noticed that the token is not automatically refreshed when the test suite is ran and every time before executing the test suite I need to manually create new token using the get token option.
Is there any option in automating the process is creating the authorization token ?
I tried automating the same by adding a groovy script to the test suite. but getting the error " java.lang.NoClassDefFoundError: org/apache/ivy/util/MessageLogger"
PFB the groovy script used:
@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 = 'Your_ClientID'
def clientSecret = 'Your_Client_Screctid'
def tokenUrl = 'https://dev.test.com/oauth2/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://api.example.com')
http.request(Method.GET, ContentType.JSON) { req ->
headers['Authorization'] = "Bearer $accessToken"
response.success = { resp, reader ->
// Handle the API response
println resp.data
}
}
}