kidman01
kidman01

Reputation: 945

Using the auth0 /oauth/token endpoint from python

I'm trying to figure out how Auth0 works. So far I'm not lucky. What I am trying to achieve is simple: POST to the oauth/token endpoint and receive a token in return. With curl this is no problem. I can curl --request POST [...] and receive a token just fine. When I try to do this using python and pythons requests module I'm getting an error stating that I'm not authorized. The data is exactly the same, I double checked. Here's my python code:

import json, requests

endpoint = 'https://mydomain.auth0.com/oauth/token'
data = {
    'grant_type': 'password',
    'username': 'myuser',
    'password': 'mypassword',
    'audience': '',
    'scope': 'read:sample',
    'client_id': 'myclientid',
    'client_secret': 'myclientsecret'
},
headers = {'content-type': 'application/json'}

response = requests.post(url=endpoint, data=json.dumps(data), headers=headers)
print("STATUS: ", response.status_code)
print("Response: ", response.json())

Working Curl request:

curl --request POST \\
  --url 'https://mydomain.auth0.com/oauth/token' \\
  --header 'content-type: application/json' \\
  --data '{"grant_type":"password","username": "myuser","password": "mypassword","audience": "", "scope": "read:sample", "client_id": "myclientid", "client_secret": "myclientsecret"}'

I also tried setting the user agent in my python code to "curl/7.51.0", but that also did not work :D

I'm happy with any pointer!

EDIT:

I shamefully have to admit that I did not use the same username afterall. That didn't change the fact though that I could not authorize myself with the python code. The SDK as suggested by @cricket_007 works fine. I find this a little bit weird but well.

Upvotes: 2

Views: 2359

Answers (2)

Thomas
Thomas

Reputation: 1219

I now the question was a long time ago but this is simply an issue with data= it should be replaced with json=

The request becomes:

response = requests.post(endpoint, json=data, headers=headers)

And you save a json.dumps.

Upvotes: 0

abigperson
abigperson

Reputation: 5362

I think this is actually a simple error in your usage of requests.post()

url is not a key word argument:

response = requests.post(endpoint, data=json.dumps(data), headers=headers)

should work here...

Upvotes: 1

Related Questions