OAuth Client 400 Error

Hi,

I am trying to use an OAuth client in Python

The following cURL command works:

curl --location --request POST 'https://sso.dynatrace.com/sso/oauth2/token' --
header 'Content-Type: application/x-www-form-urlencoded' --data-urlencode 'grant_type=client_credentials' --data-ur
lencode 'client_id=dt0s02.<ID>' --data-urlencode 'client_secret=dt0s02.<SECRET>' --data-urlencode 'resource=urn:dtaccount:<ACCOUNT>' -
-data-urlencode 'scope=<POLICIES SPACE SEPARATED>'

However, the following Python POST request gives me a 400 error.

headers = {
    "Content-Type": "application/x-www-form-urlencoded"
}

data = {
    "grant_type": "client_credentials",
    "client_id": client_id,
    "client_secret": client_secret,
    "scope": scope,
    "resource": resource
}

encoded_data = urlencode(data)

print(encoded_data)

bearer_token = requests.post(oauth_api_url, data=encoded_data, headers=headers, verify=False)
print(bearer_token)

Variables are all defined correctly same as values used in cURL command.

Can anyone see where I’m going wrong?
Thanks.

Probably you should not urlencode the data, but just send it. The HTTP/400 is common when the policies are incorrectly specified, which might be a result of the URL encoding when it is not needed.

Turns out my ENV variable for the scope had an extra space hiding in the middle of one of the scopes
Feel very silly now :laughing:
Thanks for your response, yes I’ve also removed the unnecessary encoding.