auth0-samples / auth0-python-api-samples Goto Github PK
View Code? Open in Web Editor NEWAuth0 Integration Samples for Python REST API Services using Flask
Home Page: https://auth0.com/docs/quickstart/backend/python
License: MIT License
Auth0 Integration Samples for Python REST API Services using Flask
Home Page: https://auth0.com/docs/quickstart/backend/python
License: MIT License
The variable API_ID hasn't the appropriate name in the quickstart sample project.
That can be seen in the following files:
.env
readme.md
server.py
And Missing file location at the top of the snippet code
Also, the variable is not properly filled.
The correct name for this variable is: AUTH0_AUDIENCE
Missing file location at the top of the snippet code
In the test for "Token with invalid signature", for both /api/private
and /api/private-scoped
endpoints, the returned code should be 401, but in both cases I got error 400.
Full display of the test:
Hi, I'm trying this example:
https://github.com/auth0-samples/auth0-python-api-samples/tree/master/00-Starter-Seed
in python 3.11
and I got error:
Traceback (most recent call last):
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\flask\app.py", line 2552, in __call__
return self.wsgi_app(environ, start_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\mysocketio.py", line 43, in __call__
return super(_SocketIOMiddleware, self).__call__(environ,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\engineio\middleware.py", line 74, in __call__
return self.wsgi_app(environ, start_response)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\flask\app.py", line 2532, in wsgi_app
response = self.handle_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\flask_cors\extension.py", line 176, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\flask\app.py", line 2529, in wsgi_app
response = self.full_dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\flask\app.py", line 1825, in full_dispatch_request
rv = self.handle_user_exception(e)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\flask_cors\extension.py", line 176, in wrapped_function
return cors_after_request(app.make_response(f(*args, **kwargs)))
^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\flask\app.py", line 1823, in full_dispatch_request
rv = self.dispatch_request()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\app_init.py", line 95, in login
return oauth.auth0.authorize_redirect(redirect_uri=url_for("callback", _external=True))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\authlib\integrations\flask_client\apps.py", line 43, in authorize_redirect
rv = self.create_authorization_url(redirect_uri, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\authlib\integrations\base_client\sync_app.py", line 309, in create_authorization_url
metadata = self.load_server_metadata()
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Work\exedevelopment\infinity_twin\infinity_twin_backend\venv\Lib\site-packages\authlib\integrations\base_client\sync_app.py", line 293, in load_server_metadata
with self.client_cls(**self.client_kwargs) as session:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: authlib.integrations.requests_client.oauth2_session.OAuth2Session() argument after ** must be a mapping, not tuple
My reqirements:
cryptography==37.0.4
Werkzeug==2.3.7
Flask==2.2.5
pyjwt==2.6.0
requests==2.28.0
asgiref==3.6.0
SQLAlchemy==2.0.21
pillow==9.5.0
#icecream==2.1.3
#numpy==1.26.2
#matplotlib==3.8.1
#fpdf==1.7.2
azure-storage-blob==12.15.0
azure-data-tables==12.4.2
Flask-SQLAlchemy==3.1.1
Flask-SocketIO==5.3.6
Flask-Cors==4.0.0
flask-login==0.6.2
Flask-Bcrypt==1.0.1
websocket-client
pymongo==4.6.0
gevent==23.9.1
openpyxl==3.1.2
pytz==2023.3.post1
authlib>=1.0
#---kvoli icecreamu
pygments==2.17.2
asttokens==2.4.1
#-----------diff---------
pandas==2.0.3
Run the example...
In the log there are things like Cors and Socketio, but don't worry I tried this also with disabled ones
There is no license provided with these examples, so it's unclear if a user can grab the source as a starting point. A permissive license should be applied to these repositories if that is the intention.
I followed your tutorial and ran into some problems while running tests for my application. The flask_cors.cross_origin
doesn't have an option called headers
(for reference, here).
I'm just really confused now because it should not work (when taking the original documentation as reference).
Here the error I get (To clear confusion, the error is spit out by pytest):
WARNING flask_cors.core:core.py:362 Unknown option passed to Flask-CORS: headers
Am I not getting something or should it actually be allow_headers
?
EDIT: I forgot to say, Thank you so much for the great work you're putting in here! Such tutorials are much appreciated.
In the example, the flask app is a public variable APP
, which is used to set the error handler in the decorator:
@APP.errorhandler(AuthError)
def handle_auth_error(ex):
...
What's the best way to do this if I don't have a public APP
variable for my Flask app but instead an app factory function create_app
, which returns the app?
In this file, the code is using flask._app_ctx_stack.top.current_user
I think it should be flask._request_ctx_stack.top.current_user
Right?
Wouldn't we want the current_user to be in the current request context and not the whole app's context?
Hi Auth0!
I was just upgrading my app to Flask 2.2, and I got an error about being able to import _request_ctx_stack
. It looks like that variable was removed in flask 2.2
- The app and request contexts are managed using Python context vars directly rather than Werkzeug’s LocalStack. This should result in better performance and memory use. #4682
- Extension maintainers, be aware that _app_ctx_stack.top and _request_ctx_stack.top are deprecated. Store data on g instead using a unique prefix, like g._extension_name_attr.
https://flask.palletsprojects.com/en/2.2.x/changes/
Can you please update the example to be compatible with the latest flask release? I'm not familiar with flask extension maintenance, so I'm not sure how to fix the issue.
Thanks!
the examples now require SSL because the application setup settings
now demand https://....
app.run(**{
"host": "0.0.0.0",
"port": 443,
"debug": False,
"threaded": True,
"processes": 1,
"ssl_context": "adhoc"
})
You must change some of the port and .env
values too for this to all work.
Trying to send a passwd reset email to a list of users. Is there currently a way to do this in here?
Would it be using a password change template and applying it to a send_verification_email job?
When using the sample code snippet pylint (in default configuration) complains about some issues:
************* Module server
server.py:170:0: C0301: Line too long (127/100) (line-too-long)
server.py:24:0: C0115: Missing class docstring (missing-class-docstring)
server.py:25:4: W0231: init method from base class 'Exception' is not called (super-init-not-called)
server.py:31:0: C0116: Missing function or method docstring (missing-function-docstring)
server.py:48:4: R1720: Unnecessary "elif" after "raise" (no-else-raise)
server.py:81:0: C0103: Argument name "f" doesn't conform to snake_case naming style (invalid-name)
server.py:92:12: W0707: Consider explicitly re-raising using the 'from' keyword (raise-missing-from)
server.py:121:16: W0707: Consider explicitly re-raising using the 'from' keyword (raise-missing-from)
server.py:124:16: W0707: Consider explicitly re-raising using the 'from' keyword (raise-missing-from)
server.py:129:16: W0707: Consider explicitly re-raising using the 'from' keyword (raise-missing-from)Your code has been rated at 8.84/10
I know this repository just contains just a little bit more than ~100 lines of actual business logic but anyways: If I use it in more than one project I have to copy paste the code each time. Is there a chance to make the code available as a little python package from which I could import
get_token_auth_header
requires_scope
requires_auth
AuthError
This line https://github.com/auth0-samples/auth0-python-api-samples/blob/master/00-Starter-Seed/server.py#L103 defines audience
as the unique identifier for the API, which is a URL.
However, when I paste the JWT token into jwt.io, audience is actually the ID of my SPA client. (I use Angular 1)
Needless to say I'm getting an jose.exceptions.JWTClaimsError: Invalid audience
I got this error while running your sample code.
File "C:\Python34\lib\site-packages\jwt\api_jwt.py", line 61, in decode
payload, signing_input, header, signature = self._load(jwt)
File "C:\Python34\lib\site-packages\jwt\api_jws.py", line 138, in _load
raise DecodeError('Not enough segments')
File "C:\Python34\lib\site-packages\jwt\api_jws.py", line 135, in _load
signing_input, crypto_segment = jwt.rsplit(b'.', 1)
ValueError: need more than 1 value to unpack
It seems like api_jws expects token value to contain b'.'
But my token was just ZSuxk8aa8KAh5idJ
Any idea?
P.S. I just checked the pyjwt library, and it says that it needs comma-based token value.
http://pyjwt.readthedocs.io/en/latest/
>>> import jwt
>>> jwt.encode({'some': 'payload'}, 'secret', algorithm='HS256')
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg'
>>> jwt.decode('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzb21lIjoicGF5bG9hZCJ9.4twFt5NiznN84AWoo1d7KO1T_yoc0Z6XOpOVswacPZg', 'secret')
{'some': 'payload'}
I'm using code that is based on the sample and am wondering how to properly unittest endpoints of my flask app if they are "behind" the auth.
Is there an easy mock/patch available or a best practice regarding this?
Hi,
I am trying to validate the signature of AzureAD issued access tokens using thecode described here: https://github.com/auth0-samples/auth0-python-api-samples/blob/master/00-Starter-Seed/server.py#L113
Python raises in this line https://github.com/auth0-samples/auth0-python-api-samples/blob/master/00-Starter-Seed/server.py#L113 with
Traceback (most recent call last):
File "/home/vagrant/anaconda3/lib/python3.7/site-packages/jose/jws.py", line 269, in _verify_signature
raise JWSSignatureError()
jose.exceptions.JWSSignatureError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/vagrant/anaconda3/lib/python3.7/site-packages/jose/jwt.py", line 154, in decode
payload = jws.verify(token, key, algorithms, verify=verify_signature)
File "/home/vagrant/anaconda3/lib/python3.7/site-packages/jose/jws.py", line 80, in verify
_verify_signature(signing_input, header, signature, key, algorithms)
File "/home/vagrant/anaconda3/lib/python3.7/site-packages/jose/jws.py", line 271, in _verify_signature
raise JWSError('Signature verification failed.')
jose.exceptions.JWSError: Signature verification failed.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 7, in <module>
File "/home/vagrant/anaconda3/lib/python3.7/site-packages/jose/jwt.py", line 156, in decode
raise JWTError(e)
jose.exceptions.JWTError: Signature verification failed.
I am using an implicit flow and acquire tokens using https://oidcdebugger.com/debug.
Currently I am trying to validate the signature of the (access) token.
For keys I am using the endpoint described in the metadata endpoint: https://login.microsoftonline.com/{tenant_id}/discovery/v2.0/keys
kid
matched the one of the token headerkid
, kty
, use
, n
, e
jose.jwt.decode
I don't understand why the singatures dont match. Am I using the wrong ones?
The link to the heroku app and 'this other seed project' are both broken.
I'd be great to have some unittests for the @requires_auth
decorator and the relevant methods. I wrote some in my project but they require a little bit restructuring and separating the logic into more but smaller methods. Would you accept a PR that changes the code to be easily testable?
Found that the CORS headers in server.py say 3000 but the server is running on port 3010. Shouldn't the header be set to match?
@cross_origin(headers=["Access-Control-Allow-Origin", "http://localhost:3000"])
Dependabot couldn't authenticate with https://pypi.python.org/simple/.
You can provide authentication details in your Dependabot dashboard by clicking into the account menu (in the top right) and selecting 'Config variables'.
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.