Coder Social home page Coder Social logo

auth0-samples / auth0-python-api-samples Goto Github PK

View Code? Open in Web Editor NEW
108.0 25.0 81.0 78 KB

Auth0 Integration Samples for Python REST API Services using Flask

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

License: MIT License

Python 93.29% PowerShell 1.30% Shell 1.58% Dockerfile 3.54% Procfile 0.29%
auth0 quickstart api python flask authentication dx-sdk-quickstart

auth0-python-api-samples's Introduction

Auth0 + Python Api

CircleCI

This repository contains the source code for the Python API Quickstart.

What is Auth0?

Auth0 helps you to easily:

  • implement authentication with multiple identity providers, including social (e.g., Google, Facebook, Microsoft, LinkedIn, GitHub, Twitter, etc), or enterprise (e.g., Windows Azure AD, Google Apps, Active Directory, ADFS, SAML, etc.)
  • log in users with username/password databases, passwordless, or multi-factor authentication
  • link multiple user accounts together
  • generate signed JSON Web Tokens to authorize your API calls and flow the user identity securely
  • access demographics and analytics detailing how, when, and where users are logging in
  • enrich user profiles from other data sources using customizable JavaScript rules

Why Auth0?

Create a free account in Auth0

  1. Go to Auth0 and click Sign Up.
  2. Use Google, GitHub or Microsoft Account to login.

Issue Reporting

If you have found a bug or if you have a feature request, please report them at this repository issues section. Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

License

This project is licensed under the MIT license. See the LICENSE file for more info.

auth0-python-api-samples's People

Contributors

aaguiarz avatar alexisluque avatar annyv2 avatar chenkie avatar damieng avatar danidee10 avatar dependabot-preview[bot] avatar evansims avatar hf-kklein avatar infinitewarp avatar joshcanhelp avatar jrnp97 avatar lbalmaceda avatar paulioceano avatar rafanog avatar saltukalakus avatar sergiught avatar vmartynets avatar widcket avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

auth0-python-api-samples's Issues

I can't get the 00-starter-seed python example to work (singature verification failed)

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

  1. I extract the key where kid matched the one of the token header
  2. I construct the dict with kid, kty, use, n, e
  3. then use it with jose.jwt.decode

I don't understand why the singatures dont match. Am I using the wrong ones?

Getting error 400 during test

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.

screenshot_1

Full display of the test:

test.txt

Error calling jwt.Decode

When calling Python API always throws exception jwt.DecodeError on jwt.decode(token,secret,audience).

image

'headers' is an unknown option - Flask-CORS

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.

Make this code available as a package

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

Add Unittests for requires_auth decorator

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?

Flask API: Wrong endpoint in README file

In the README file, the endpoints shown are not /api/public, /api/private and /api/private-scoped.

the endpoints /secured/ping and /secured/private/ping are not consistend wih the other API samples

capture 2018-02-03 at 17 40 05

Code does not obey Pylint rules

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

Add license to examples

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.

Auth0 Example is not working

Checklist

  • I have looked into the Readme and have not found a suitable solution or answer.
  • I have searched the issues and have not found a suitable solution or answer.
  • I have searched the Auth0 Community forums and have not found a suitable solution or answer.
  • I agree to the terms within the Auth0 Code of Conduct.

Description

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


image

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

Reproduction

Run the example...

Additional context

In the log there are things like Cors and Socketio, but don't worry I tried this also with disabled ones

Failed to decode in jwt

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'}

Is there a way to send password reset email?

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?

CORS header port 3000, should be 3010

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"])

Set error handler without public APP variable

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?

Backend Python: Several problems with the API_ID variable.

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

image

Flask example no longer compatible with flask 2.2

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!

Add SSL handling

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.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.