OAuth 2.0 generate token


I am trying to call an endpoint which generates bearer token which will be used for calling another endpoint for OAuth 2.0 authentication using the bearer token generated from the first endpoint.
The generate token api call works in postman but when i use system.net.httppost method, pass the necessary parameters, i get http error 400.
Below is the code I am using-

Generate Bearer Token

authServerURL = "MyURLToGenerateBearerToken"
clientId = "MyClientId"
clientSecret = "MyClientSecret"
payload = {"grant_type": "client_credentials","client_id" : clientId,"client_secret":clientSecret}
headerValues = {"Content-Type" : "application/x-www-form-urlencoded"}

# convert payload to URL-encoded form	
encodedPayload = ",".join(key + "=" + str(val) for key, val in payload.items())

#payload1 = {"grant_type": "client_credentials"}

authResponse = system.net.httpPost(url=authServerURL,postData=encodedPayload,headerValues = headerValues)

I tried passing payload, payload1 and encodedPayload as postData value in the http.post method but I get the same error -

IOError: Server returned HTTP response code: 400 for URL: MyURLToGenerateBearerToken

What am I writing wrong?
Could anyone please help me with this?

The first thing I'd recommend is refactoring the above to use system.net.httpClient to perform your POST request. The Response object you get back from the call might be able to give you more details on the 400 (Bad Request) error that you're getting from the server.

Ultimately, it is up to the endpoint you're working with to define how your request needs to be structured. If you already have a working example from Postman, do a careful comparison of where you're feeding in URL Query Parameters, Request Headers and Body/Payload.

Make sure to map these to the corresponding elements in your Ignition request. Below is a guess at a possible solution (impossible to really know without more information on the endpoint you're communicating with or the example Postman request):

# Configuration
authServerURL = "MyURLToGenerateBearerToken"  # should be HTTPS
clientId = "MyClientId"
clientSecret = "MyClientSecret"
queryParams = {"grant_type": "client_credentials","client_id" : clientId,"client_secret":clientSecret}
headerValues = {"Content-Type" : "application/x-www-form-urlencoded"}

logger = system.util.getLogger("org.example.comms.someUsefulName")

# Send a POST request.
client = system.net.httpClient()
response = client.post(authServerURL, params=queryParams, headers=headerValues)
# Validate the response.
if response.good:
    logger.debugf("Request completed successfully, response code %d", response.statusCode)
    # ... do things you need to do with the `response`
    logger.warnf("Request errored, response code %d: %s", response.statusCode, response.text)
1 Like