I'm trying to make an authentication code to an API using a token (OAuth2). The problem I have is that the API gives me a token of length 664, which is not valid and when I try to access the other API using that token, I get error 403. For some strange reason, when I make the call through Postman to get that token, it gives me a longer token and if I use that token that postman gives me in my code, I get access to the API without problems, it seems that for some reason my python code is truncating the token (?).
Here is my code:
def get_auth_token(url):
"""
get an auth token
"""
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
data = {
'grant_type': 'client_credentials',
'username': "john.doe",
'password': "yuppy_duppy.*",
'audience': 'https://website-token.com',
'scope' : '',
'client_id' : 'foo-api-client',
'client_secret': 'bEeuADqpubMoPos6eLYd6UEMx'
}
try:
response = requests.post(url, headers=headers, data=data)
response.raise_for_status()
token = response.json()['access_token']
print(response.raw)
return token
except requests.exceptions.HTTPError as errh:
print(errh)
except requests.exceptions.ConnectionError as errc:
print(errc)
except requests.exceptions.Timeout as errt:
print(errt)
except requests.exceptions.RequestException as err:
print(err)
token = get_auth_token('https://url-to-request-token.com/token')
head = {'Authorization': "Bearer " + token}
request_result = requests.get(URL_ZOOM, headers=head)
print(request_result.status_code)
and the status code result:
>> 403
I validated the call request in Postman against my call parameters and they do not differ at all.
What could be the reason why Postman gives me a valid token and my request to the server gives me an invalid one?
I have actually run into this several times dealing with APIs in Python, and PHP for that matter, and having everything look fine in Postman and then not work on our dev server.
Here's a trick, if you didn't already know about this, click here:
Then select your language of choice:
And it actually has two for Python depending on if you want to use requests or not. From there, you can either:
Make sure that your code Really does match the code that is working (the snippet) - by putting them right next to each other in your editor and comparing them.
Comment out your code, use the snippet, see if it works. If it doesn't work, then it might be related to something like your local variables or something else that you are setting manually when doing it in postman but having dynamically generated in production.