'How to get List of users and total from Auth0 using Python

How can I get the list of all users from an Auth0 Account and also get the total using PYTHON language?



Solution 1:[1]

Auth0 allows using an API token to obtain data. To obtain the user details including the total, you will need the API client secret and id.

Auth0 document to get the token

I've written an article here

The code to use...

import http.client
import json

client_id = 'xxxxxxxxxxxxxxxxxxxx'
client_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
business_name = 'xxxxxxxxx'

# GET THE ACCESS TOKEN using the client_id and client_secret
conn = http.client.HTTPSConnection(business_name+".eu.auth0.com")
payload = "{\"client_id\":\""+client_id+"\",\"client_secret\":\""+client_secret+"\",\"audience\":\"https://"+business_name+".eu.auth0.com/api/v2/\",\"grant_type\":\"client_credentials\"}"
headers = { 'content-type': "application/json" }
conn.request("POST", "/oauth/token", payload, headers)
res = conn.getresponse()
data = res.read()
tokendetails_json = data.decode('utf8').replace("'", '"')
# Load the JSON to a Python list & dump it back out as formatted JSON
tokendetails = json.loads(tokendetails_json)


#NOW GET THE USERS AND TOTAL
conn = http.client.HTTPSConnection(business_name+".eu.auth0.com")
payload = "{\"client_id\":\""+client_id+"\",\"client_secret\":\""+client_secret+"\",\"audience\":\"https://"+business_name+".eu.auth0.com/api/v2/\",\"grant_type\":\"client_credentials\"}"
headers = { 'content-type': "application/json","Authorization": "Bearer "+tokendetails['access_token'] }
conn.request("GET", "/api/v2/users?include_totals=true", payload, headers)
res = conn.getresponse()
data = res.read()
result_data_json = data.decode('utf8').replace("'", '"')

# Load the JSON to a Python list & dump it back out as formatted JSON
result_data = json.loads(result_data_json)
print(result_data)                  # Json list of all users
print(result_data['total'])         # Just the count of total users

Solution 2:[2]

Got sydadder code to work after enabling a test application and then giving read permissions here: Auth0 dashboard / Applications / APIs / Machine to Machine Applications / Auth0 Management API (Test Application) (expand by clicking on down-arrow)

Without adjusting permissions I got:

{'statusCode': 401, 'error': 'Unauthorized', 'message': 'Invalid token', 'attributes': {'error': 'Invalid token'}}

Plus altering "eu.auth0.com" throughout to the appropriate Auth0 region.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 sydadder
Solution 2 saskwoch