auth0 / auth0-python Goto Github PK
View Code? Open in Web Editor NEWAuth0 SDK for Python
Home Page: https://auth0-python.readthedocs.io
License: MIT License
Auth0 SDK for Python
Home Page: https://auth0-python.readthedocs.io
License: MIT License
It seems like https://auth0.com/docs/api/management/v2#!/Logs/get_logs is missing in the management api.
It would be great if this can be added.
The auth0 node.js client got support for the get_users_by_email about 3 weeks ago (auth0/node-auth0@80c9b0c).
This is pretty critical for us because the way we are currently searching for users (using the get_users API with search_engine=v2
and [email protected]
) no longer works.
Would be nice to generate valid links for impersonation of users via the API
I am getting a 400
ERROR when working with the from auth0.v3.authentication.passwordless import Passwordless
class as it looks like the AuthenticationBase
does not set the headers properly for some reason?
Has anyone figured out away to pass the auth0
class from the documentation so I can just pass my client id only.
data = {
'client_id': auth0.clients.domain
}
p = Passwordless(data['client_id'])
o = p.sms(data['client_id'], phone_number) # I get the 400 error here
When testing the API with JQuery I received a CORS issue, which was fixed by adding @cross_origin(headers=['Access-Control-Allow-Origin', '*'])
The logic in authorize_client
seems to both generate the authorize url as well as call it. In the case of sending a redirect to the user, it would be ideal to just be able to generate the URL and then return a 302 directing the url the composed URL.
auth0-python/auth0/v3/authentication/authorize_client.py
Lines 15 to 32 in cbce31b
The response from the change_password request has changed within the last 24 hours of writing this. The response from a change request is not just a text string, not a JSON.
request.text is "We've just sent you an email to reset your password."
The documentation at [https://auth0.com/docs/api/authentication#change-password] agrees.
The _process_request method in AuthenticationBase attempts to parse it to a JSON String:
Line 17 - text = json.loads(response.text) if response.text else {}
Which raises :
ValueError: Expecting value: line 1 column 1 (char 0)
...(snippet)
File "C:\awt-opt\windows\virtualenv\lib\site-packages\auth0\v3\authentication\base.py", line 17, in _process_response
text = json.loads(response.text) if response.text else {}
I'm getting the following error: auth0.v3.exceptions.Auth0Error: 400: Bad HTTP authentication header format
.
This is the code I'm using (anonymized):
get_token = GetToken('my-domain.eu.auth0.com')
token = get_token.client_credentials('my-client-id',
'my-client-secret',
'https://my-domain.eu.auth0.com/api/v2/')
auth0 = Auth0('my-domain.eu.auth0.com', token)
auth0.users.create({...})
In my Auth0 logging, I can see the token was created succesfully:
Type: Success Exchange
Description: Client Credentials for Access Token
I've also printed out the Authorization
header that the auth0-python package (rest.py module) uses and it seems correct (i.e. Bearer: <token>
):
Bearer {'access_token': 'a-long-token', 'expires_in': 86400, 'scope': 'read:client_grants create:client_grants delete:client_grants update:client_grants read:users update:users delete:users create:users read:users_app_metadata update:users_app_metadata delete:users_app_metadata create:users_app_metadata create:user_tickets read:clients update:clients delete:clients create:clients read:client_keys update:client_keys delete:client_keys create:client_keys read:connections update:connections delete:connections create:connections read:resource_servers update:resource_servers delete:resource_servers create:resource_servers read:device_credentials update:device_credentials delete:device_credentials create:device_credentials read:rules update:rules delete:rules create:rules read:email_provider update:email_provider delete:email_provider create:email_provider blacklist:tokens read:stats read:tenant_settings update:tenant_settings read:logs read:shields create:shields delete:shields update:triggers read:triggers read:grants delete:grants read:guardian_factors update:guardian_factors read:guardian_enrollments delete:guardian_enrollments create:guardian_enrollment_tickets read:user_idp_tokens', 'token_type': 'Bearer'}
Any ideas on what I'm doing wrong or how to fix this?
Hi,
I have enable a field "Requires Username" in database connection but the problem is how to pass the username field in the request ?
I use Database Endpoint :
database = Database(domain='domain.eu.auth0.com')
response = database.signup(
client_id="client_id",
email="[email protected]",
password="totototo",
connection="Username-Password-Authentication",
)
It's possible to use this feature ?
Thank you,
The seed project of the flask-webapp sample uses not session.has_key(‘profile’) which is not compatible with Python 3 and produces an error when trying to use server.py
The issue tracking, author and license sections should be together and at the bottom of the readme file.
Also the license link in the readme is broken.
I have this very simple requirements.txt
auth0-python==3.0.0
and when installing the dependencies (a part of a jenkins job) by running pip3 install -r jenkinsfiles/auth0-users/requirements.txt
it fails. I don't get much back a part from the -1
unfortunately:
+ venv/bin/pip3 install -r jenkinsfiles/auth0-users/requirements.txt
Collecting auth0-python==3.0.0 (from -r jenkinsfiles/auth0-users/requirements.txt (line 1))
Downloading auth0-python-3.0.0.tar.gz
Collecting requests (from auth0-python==3.0.0->-r jenkinsfiles/auth0-users/requirements.txt (line 1))
Downloading requests-2.13.0-py2.py3-none-any.whl (584kB)
Building wheels for collected packages: auth0-python
Running setup.py bdist_wheel for auth0-python: started
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code -1
Finished: FAILURE
Versions of python, pip, etc...:
Seems to work fine locally and work intermitetntlly in jenkins.
I wonder if it's a connectivity problem or on PyPi's end. Any ideas?
Hi, Could you please let me know if there is a function to get all the user_id for a specific app? Thanks.
I want to deploy an app and add new users later on. In this case, I need a function to check all the user_id for authentication status. Thanks.
Currently Auth0Error
is raised whenever the API response contains an error
key in the response JSON. Unfortunately at least one endpoint (/dbconnections/signup
) returns inconsistent error messages (that do not always contain the error
key) for different scenarios and as a result Auth0Error
is not raised when an error occurs.
Examples of inconsistent responses:
{
"code": "user_exists",
"description": "The user already exists.",
"name": "BadRequestError",
"statusCode": 400
}
client_id
(with public signup disabled){
"name": "NotFoundError",
"statusCode": 404
}
{
"code": "invalid_password",
"description": {
"rules": [
{
"code": "lengthAtLeast",
"format": [
6
],
"message": "At least %d characters in length",
"verified": false
}
],
"verified": false
},
"message": "Password is too weak",
"name": "PasswordStrengthError",
"policy": "* At least 6 characters in length",
"statusCode": 400
}
{
"error": "password is required"
}
The last example highlights a related issue. Even though there is an error
key, a KeyError
exception will ultimately occur because AuthenticationBase._process_response
assumes the additional existence of an error_description
key when creating the Auth0Error
and setting its message.
I've got a traceback:
In [78]: user_authentication.tokeninfo(id_token)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-78-decf4417ce18> in <module>()
----> 1 user_authentication.tokeninfo(id_token)
/home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/auth0/v2/authentication/users.pyc in tokeninfo(self, jwt)
47 url='https://%s/tokeninfo' % self.domain,

48 data={'id_token': jwt},
---> 49 headers={'Content-Type: application/json'}
50 )
/home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/auth0/v2/authentication/base.pyc in post(self, url, data, headers)
8 def post(self, url, data={}, headers={}):
9 response = requests.post(url=url, data=json.dumps(data),
---> 10 headers=headers)
11 return self._process_response(response)
12
/home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/api.pyc in post(url, data, json, **kwargs)
107 """
108
--> 109 return request('post', url, data=data, json=json, **kwargs)
110
111
/home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/api.pyc in request(method, url, **kwargs)
48
49 session = sessions.Session()
---> 50 response = session.request(method=method, url=url, **kwargs)
51 # By explicitly closing the session, we avoid leaving sockets open which
52 # can trigger a ResourceWarning in some cases, and look like a memory leak
/home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/sessions.pyc in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert, jso
n)
452 hooks = hooks,
453 )
--> 454 prep = self.prepare_request(req)
455
456 proxies = proxies or {}
/home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/sessions.pyc in prepare_request(self, request)
386 auth=merge_setting(auth, self.auth),
387 cookies=merged_cookies,
--> 388 hooks=merge_hooks(request.hooks, self.hooks),
389 )
390 return p
/home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/models.pyc in prepare(self, method, url, headers, files, data, params, auth, cookies, hooks, json)
292 self.prepare_method(method)
293 self.prepare_url(url, params)
--> 294 self.prepare_headers(headers)
295 self.prepare_cookies(cookies)
296 self.prepare_body(data, files, json)
/home/ale/.virtualenvs/auth0/lib/python2.7/site-packages/requests/models.pyc in prepare_headers(self, headers)
400
401 if headers:
--> 402 self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())
403 else:
404 self.headers = CaseInsensitiveDict()
AttributeError: 'set' object has no attribute 'items'
Max is 100 using auth0.users.list, what's the best way to get them all?
We've encountered issues in our production environment for weeks and after some digging, released that calls to requests.get()
and requests.post()
and missing the timeout
parameter, causing the server to hang indefinitely on occasion if no response is received.
In our specific case, the problem is with these instances:
class AuthenticationBase(object):
def post(self, url, data=None, headers=None):
response = requests.post(url=url, data=json.dumps(data),
headers=headers)
return self._process_response(response)
def get(self, url, params=None, headers=None):
return requests.get(url=url, params=params, headers=headers).text
but there may well be others.
As noted on the requests documentation:
Nearly all production code should use this parameter in nearly all requests. Failure to do so can cause your program to hang indefinitely
Unlike the other endpoint classes (e.g., Users
, Connections
), the UserBlocks
class is not instantiated in the root Auth0
object. Is this by design? Culprit line seems to be here: https://github.com/auth0/auth0-python/blob/master/auth0/v3/management/auth0.py#L43
I would expect to fetch a user's blocks like so
auth0.user_blocks.get('auth0|idhere')
since I fetch users like this:
auth0.users.get('auth0|idhere')
But instead I have to pass the domain/token to the auth0.users_blocks
class myself
The app.js file has an outdated comment: "// All this properties are set on auth0-variables.js". Those properties are currently set on a .env file.
The readme.md file doesn't explain that for the seed project to work on Windows the .env file (in the case that it has to be created by the user) needs to have a newline in the end, after the URL.
I am trying to settle a server for a react-native app based on examples/flask-api. it seems that server.py accepts requests as GET data. I want to learn two things. Is using GET safe enough? Can I use POST requests for more security?
Flask web app example is using lock 7.11, current version is 7.12
Currently there isn't support to get, create, update, and delete rule settings/configs.
https://auth0.com/docs/api/management/v2#!/Rules_Configs/get_rules_configs
from auth0.v3.authentication import Social
social = Social('https://my-tenant.eu.auth0.com')
social.login(client_id='secret', access_token='secret', connection='google')
Using Python 3.5 this results in:
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='https', port=443): Max retries exceeded with url: //my-tenant/oauth/access_token Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7f43b39f3cc0>: Failed to establish a new connection: [Errno 110] Connection timed out',))
One is able to install from PyPi, but it is not clear which SHA pertains to which release. Adding tags for the relevant published versions would be extremely helpful for an end user.
I notice that Flask API Seed example only works when I pass "audience=CLIENT_ID" into jwt.decode(). I'm not sure if it's something with my configuration, but I consistently hit an InvalidAudienceError when I auth via Google+ if I fail to include this as a parameter.
SDK should return the info that Auth0 returns on HTTP headers about rate limiting, so calling program can dynamically adjust the rate at which it makes subsequent API calls (that are rate limited)
Here is the documentation on what programs are supposed to do:
https://auth0.com/docs/rate-limits
SDK should return the info to enable that.
Had there been a change to Auth0 error messages? For duplicate user creation, a message as 'Conflict' instead of 'The user already exists.' is quite vague.
I had a check based on Auth0Error.message field, which is failing now, for user creation with duplicate email.
Could you help!
I am on python2.7. The get_token.client_credentials has always worked for me using v3.1.4.
I upgraded to 3.2.0 and I get the following error when calling client_credentials:
File "/Users/faria/w/nsplab/orbit-server/scripts/auth0_users.py", line 19, in connect
token = get_token.client_credentials(client_id, client_secret, mgmt_url)
File "/Users/faria/.virtualenvs/orbit/lib/python2.7/site-packages/auth0/v3/authentication/get_token.py", line 120, in client_credentials
headers={'Content-Type': 'application/json'}
File "/Users/faria/.virtualenvs/orbit/lib/python2.7/site-packages/auth0/v3/authentication/base.py", line 12, in post
return self._process_response(response)
File "/Users/faria/.virtualenvs/orbit/lib/python2.7/site-packages/auth0/v3/authentication/base.py", line 18, in _process_response
return self._parse(response).content()
File "/Users/faria/.virtualenvs/orbit/lib/python2.7/site-packages/auth0/v3/authentication/base.py", line 24, in _parse
return JsonResponse(response)
File "/Users/faria/.virtualenvs/orbit/lib/python2.7/site-packages/auth0/v3/authentication/base.py", line 47, in init
super().init(response.status_code, content)
TypeError: super() takes at least 1 argument (0 given)
It does not look like delete_users_by_email
(aka "Delete a connection user") is currently wrapped by this library.
On upgrading from 3.1.4 to 3.2.2, error messages from users.create
went from being helpful like this:
Payload validation error: 'Object didn't pass validation for format email: lame_email' on property email (The user's email).
To being unhelpful, like this:
Bad Request
The Auth0 Management API supports getting all Rules or filtering by enabled/disabled. If the enabled parameter is present and set to True, only enabled rules are returned. If it is present and set to False, only disabled rules are returned. If it is not present, all rules are returned.
The python package always includes the enabled parameter in requests and thus will only return enabled rules if set to True (default) or disabled rules if set to False. There is no way to get all Rules in a single request via the Python package.
I've created a pull request that addresses this issue.
Hi, I couldn't find any method to revoke the refresh token. Isn't it built into the library?
Even though the API supports it: https://auth0.com/docs/api/authentication#signup
I am pretty sure that the actual problem is on the server side, but since I am seeing it through the Python client I am filing this here.
I am seeing and issue with the error message returned when a user has been blocked for too many authentication attempts. Namely that there is a mis-encoded right-single-quote (as in the right curly quote) in the message:
Unauthorized(u'Could not authorize with auth0 due to too_many_attempts: Your account has been blocked after multiple consecutive login attempts. We\u2019ve sent you an email with instructions on how to unblock it.',)
That is what you get if you print it with %r
, if you try to just print it (so %s
) you get:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 207: ordinal not in range(128)
There really is no need for Unicode in the error messages, so please change that. And I think that your server is also probably mis-encoding in this case.
Will this work on non-public cloud enterprise deployments of auth0?
The README states that this callback AUTH0_CALLBACK_URL=http://localhost:3000/auth/auth0/callback
should be used but it should be http://localhost:3000/callback. So a fix in the README is needed in order to explain this
It appears the following commit (7b0c7b1) broke Python 2.7 support as the urllib.parse
method is urlparse
in Python 2.7.
CONTRIBUTING.rst gives a 404
Add an all
option to the users list
method that handles pulling down all matching users (ie deals with pagination). Right that responsibility seems to be pushed onto the consumer. Further the documentation for how to get total number of pages is sparse.
We use Telemetry headers to measure the versions of the SDKs that are currently in use. I found out that for Authentication API calls, the headers are not sent in comparison to the Management API calls. I think the change needs to go into the authentication base class, following what is currently present on the management's rest client class.
A proper PR needs to have the functionality added to the current constructor, having the Telemetry boolean enabler parameter as an optional always defaulting to true
or enabled
. There should be tests asserting that default behavior and that the telemetry can be disabled.
The README is missing the install dependencies instruction on the webapp example
Flask webapp using deprecated library auth0-widget. Should be changed to auth0-lock
Hi there,
I'm trying to use the Auth0 Python SDK in my flask application but can't get the Auth0Error to work. I currently have the following code:
`import os, json, requests
from auth0.v3.authentication import GetToken
from auth0.v3.exceptions import Auth0Error
from auth0.v3.management import Auth0
auth_domain = os.getenv('DOMAIN')
auth_client_id = os.getenv('AUTH0_CLIENT_ID')
auth_client_secret = os.getenv('AUTH0_CLIENT_SECRET')
def get_token():
get_token = GetToken(auth_domain)
token = get_token.client_credentials(
auth_client_id,
auth_client_secret,
'https://{}/api/v2/'.format(auth_domain))
return token['access_token']
def create_user(token, data):
try:
user = auth0.users.create(data)
return user
except Auth0Error:
????
`
I'm importing the functions in my route function (flask). The get_token function works as expected and creating a new user also works fine. However when I try to test my route with wrong user data I can't capture the Auth0Error... how can I extract the status code and error message from the "Auth0Error exception"? What do I have to put where the questions marks are in order to get a meaningful error?
Hi,
It appears that as of late there has been some changes on how to generate tokens used by the auth0 management apis. One of the more problematic issues is that If we follow the token generation strategies within the auth0 application itself the tokens returned only appear to last for 24 hours.
I believe the previous way of generating tokens, documented in the readme of this repo, did not have this limitation. (https://github.com/auth0/auth0-python#management-sdk-usage).
This is causing some pretty serious problems for us as our application relies on this package as well as auth0 heavily. Unfortunately we did not track or raise concern for the deprecated way to generate api keys and are now using tokens that expire in our running application.
Is there a recommended strategy for automatically renewing tokens using the client id and secret? Moving forward will this package be updated to handle this or is it expected that the application take care of of the automatic token generation?
Hi,
I would like update the user password but if the request return a 400 status code, there is no exception throw "Auth0Error".
My request :
request = auth0.users.update(<id>, {
"password": "totototo"
})
I get :
{'statusCode': 400, 'error': 'Bad Request', 'message': 'PasswordHistoryError: Password has previously been used'}
But in your RestClient, you check if there is an attribute with the name "errorCode" but that doesn't work because the attribute is called "statusCode".
if isinstance(text, dict) and 'errorCode' in text:
raise Auth0Error(status_code=text['statusCode'],
error_code=text['errorCode'],
message=text['message'])
is it normal ???
Rather than:
send_verification_email(self, body)
I suggest:
send_verification_email(self, user_id)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.