1

I'm trying to run unit tests in Python for my flask application for routes that depend on the userID which is obtained from the access_token.

Is there a way to call the auth0 authorize API, in Python, to obtain an access_token for a user given their username and password?

If not, then what is an automated way of calling the authorize API to give it a username and password and obtain an access_token?

A code snippet would be best.

dim_voly
  • 478
  • 2
  • 10
  • 20

2 Answers2

2

Thanks to @Jerdog, I've constructed the required piece of code:

import json
import requests

# testing user password database:
testingUsers = {
    'testingUser2@funnymail.com': 'BuQ3tUS3 :jbFAL',
    'testingUser3w@funnymail.com': 'y(1726854(b(-KY'
    }


def getUserToken(userName):
    # client id and secret come from LogIn (Test Client)! which has password enabled under "Client > Advanced > Grant Types > Tick Password"
    url = 'https://YOUR_AUTH0_DOMAIN/oauth/token' 
    headers = {'content-type': 'application/json'}
    password = testingUsers[userName]
    parameter = { "client_id":"Jfjrl12w55uqcJswWmMhSm5IG2Qov8w2e", 
                  "client_secret": "3E5ZnqLFbPUppBLQiGDjB0H2GtXaLyaD26sdk2HmHrBXQaDYE453UCUoUHmt5nWWh",
                  "audience": 'AUTH0_AUDIENCE',
                  "grant_type": "password",
                  "username": userName,
                  "password": password, "scope": "openid" } 
    # do the equivalent of a CURL request from https://auth0.com/docs/quickstart/backend/python/02-using#obtaining-an-access-token-for-testing
    responseDICT = json.loads(requests.post(url, json=parameter, headers=headers).text)
    return responseDICT['access_token']

@memoize # memoize code from: https://stackoverflow.com/a/815160
def getUserTokenHeaders(userName='testingUser2@funnymail.com'):
    return { 'authorization': "Bearer " + getUserToken(userName)} 

The @memoize decorator is to avoid multiple calls to get a token over many tests. The tenant has to have a default database specified for the above call to work (see this answer). It was a bit cryptic as to what the database name was supposed to be (the default_directory), but for me, with only Auth0 users, the database was Username-Password-Authentication, which seems to be the default for new accounts.

dim_voly
  • 478
  • 2
  • 10
  • 20
1

Have you looked at the https://auth0.com/docs/quickstart/backend/python/01-authorization walkthrough? The full quickstart for Python should give you a good start

Jeremy
  • 548
  • 1
  • 4
  • 13
  • Item 2 under [https://auth0.com/docs/quickstart/backend/python/02-using#obtaining-an-access-token-for-testing](https://auth0.com/docs/quickstart/backend/python/02-using#obtaining-an-access-token-for-testing)? So I can write a python `requests` equivalent to the curl that they've shown there? – dim_voly Jan 31 '18 at 22:54