简体   繁体   中英

Retrieving Auth0 User information

I am trying to build a python script that access the email and last logged in time data of all my users on my auth0 portal. How should i approach this? this is the code i have so far

import sys
sys.path.append("D:\home\site\wwwroot\env\Lib\site-packages")

import quickbase
import urllib2
import pypyodbc
import timestring
import datetime
import time
import math
import sys
import locale
import smtplib
import pypyodbc
import httplib
import json
import urllib
import urllib2

from dateutil.relativedelta import relativedelta

#Activate Webhook with Campaign is added or modified.
#0.1 establish connection to SQL server
connection = pypyodbc.connect('Driver={SQL Server Native Client 11.0};'
'Server=tcp:xxxxe.database.windows.net,1433;'
'Database=LQDC;'
'uid=Admin@lxx;pwd=xxxx')
cursor = connection.cursor()

#0.2 establish connection to Auth0
def main():

#Configuration Values
AUDIENCE = "https://xxe.auth0.com/api/v2/"
DOMAIN = "lxxx.auth0.com"
CLIENT_ID = "xxxxxL"
CLIENT_SECRET = "xxxxxxr"
GRANT_TYPE = "client_credentials" # OAuth 2.0 flow to use

#Get an Access Token from Auth0
base_url = "https://{domain}".format(domain=DOMAIN)
data = urllib.urlencode([('client_id', CLIENT_ID),
('client_secret', CLIENT_SECRET),
('audience', AUDIENCE),
('grant_type', GRANT_TYPE)])
req = urllib2.Request(base_url + "/oauth/token", data)
response = urllib2.urlopen(req)
oauth = json.loads(response.read())
access_token = oauth['access_token']

#Get all Applications using the token
req = urllib2.Request(base_url + "/api/v2/clients")
req.add_header('Authorization', 'Bearer ' + access_token)
req.add_header('Content-Type', 'application/json')

try:
response = urllib2.urlopen(req)
res = json.loads(response.read())
print res

conn = httplib.HTTPSConnection(DOMAIN)
payload = "{\"connection_id\":\"not sure which API/token/code to put here\",\"format\": \"csv\", \"limit\": 4, \"fields\": [{ \"name\": \"email\"},{\"name\": \"last_ip\"}, { \"name\": \"created_at\"}, { \"name\": \"last_login\"}]}"
headers = {
    'authorization': "Bearer "+access_token,
    'content-type': "application/json"
    }
conn.request("POST", "/xxxx.auth0.com/api/v2/jobs/users-exports", payload, headers)
res = conn.getresponse()
data = res.read()
print(data.decode("utf-8"))
except urllib2.HTTPError, e:
print 'HTTPError = ' + str(e.code) + ' ' + str(e.reason)
except urllib2.URLError, e:
print 'URLError = ' + str(e.reason)
except urllib2.HTTPException, e:
print 'HTTPException'
except Exception:
print 'Generic Exception'

#Standard boilerplate to call the main() function.
if name == 'main':
main()


the first part works fine, second part returns the error below im trying to have this return a csv file with all the information of users listed, and populate the database automatically with that.

also found some useful links here which i tried incorporating into my code: https://auth0.com/docs/users/guides/bulk-user-exports

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /lqdfinance.auth0.com/api/v2/jobs/users-exports</pre>
</body>
</html>

As Nishant recommended, I would guide you towards our Python quickstart for building out this type of functionality to begin with.

Depending on your overall detailed goal it may may require some deviation but it's a fantastic place to start! Please us know if you have any questions!

https://auth0.com/docs/quickstart/backend/python

As i can see i your code, you need a connection id so you can use

base_url + '/api/v2/connections'

to get your connection id Next you need to modify your payload body as below

{
  "connection_id": "your_id_as_above",
  "format": "csv",
  "limit": 5,
  "fields": [
      {
        "name": "user_id"
      },
      {
        "name": "name"
      },
      {
        "name": "email"
      },
      {
        "name": "identities[0].connection",
        "export_as": "provider"
      },
      {
        "name": "user_metadata.some_field"
      }
    ]
}

In order to test your response data i suggest you test your api payload and response using Postman, as it gives you more clarity on how the request is working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM