项目作者: joegasewicz

项目描述 :
Flask JWT Router is a Python library that adds authorised routes to a Flask app.
高级语言: Python
项目地址: git://github.com/joegasewicz/flask-jwt-router.git
创建时间: 2019-06-09T12:30:31Z
项目社区:https://github.com/joegasewicz/flask-jwt-router

开源协议:MIT License

下载


Python package
PyPI version
codecov
Codacy Badge
Documentation Status
PyPI - Python Version
GitHub license

Flask JWT Router

Read the docs: Flask-JWT-Router

Flask JWT Router

Flask JWT Router is a Python library that adds authorised routes to a Flask app. Both basic & Google’s OAuth2.0 authentication
is supported.

Google’s OAuth2.0 supported" class="reference-link">Google-Cloud Google’s OAuth2.0 supported

Quik Start

  1. from flask_jwt_router import JwtRoutes
  2. jwt_routes = JwtRoutes()
  3. jwt_routes.init_app(
  4. app,
  5. entity_models=[MyModel],
  6. )

Now your front end needs a token. Create an endpoint &
return a new access token from the clients header code.
For Example::

  1. from flask import request
  2. @app.routes("/login", methods=["POST"])
  3. def login():
  4. jwt_routes.google.oauth_login(request) # Pass in Flask's request

Now, the next time your front-end requests authorised resources
flask-jwt-router will authenticate with this access token until
it expires.

Installation

Stable version

  1. pip install flask-jwt-router

Basic Usage

  1. from flask import Flask
  2. from flask_jwt_router import JwtRoutes
  3. app = Flask(__name__)
  4. # You are required to always set a unique SECRET_KEY for your app
  5. app.config["SECRET_KEY"] = "your_app_secret_key"
  6. JwtRoutes(app)
  7. # If you're using the Flask factory pattern:
  8. jwt_routes = JwtRoutes() # Example with *entity_model - see below
  9. def create_app(config):
  10. ...
  11. jwt_routes.init_app(app)

Whitelist Routes

  1. app.config["WHITE_LIST_ROUTES"] = [
  2. ("POST", "/register"),
  3. ]
  4. @app.route("/register", methods=["POST"])
  5. def register():
  6. return "I don't need authorizing!"

Prefix your api name to whitelisted routes

  1. # All routes will
  2. app.config["JWT_ROUTER_API_NAME"] = "/api/v1"
  3. app.config["WHITE_LIST_ROUTES"] = [
  4. ("POST", "/register"),
  5. ]
  6. @app.route("/api/v1/register", methods=["POST"])
  7. def register():
  8. return "I don't need authorizing!"

Bypass Flask-JWT-Router on specified routes

  1. # Define homepage template routes for example on JWT_IGNORE_ROUTES
  2. # & still get to use the api name on request handlers returning resources
  3. app.config["IGNORED_ROUTES"] = [
  4. ("GET", "/")
  5. ]

Declare an entity model

  1. # Create your entity model (example uses Flask-SqlAlchemy)
  2. class UserModel(db.Model):
  3. __tablename__ = "users"
  4. id = db.Column(db.Integer, primary_key=True)
  5. name = db.Column(db.String)
  6. # You can define the primary key name with `ENTITY_KEY` on Flask's config
  7. app.config["ENTITY_KEY"] = "user_id"
  8. # (`id` is used by default)
  9. JwtRoutes(app, entity_models=[UserModel, TeacherModel, ...etc])
  10. # Or pass later with `init_app`
  11. def create_app(config):
  12. ...
  13. jwt_routes.init_app(app, entity_models=[UserModel, TeacherModel, ...etc])

Authorization

  1. from your_app import jwt_routes
  2. # white list the routes
  3. app.config["WHITE_LIST_ROUTES"] = [
  4. ("POST", "/register"),
  5. ("POST", "/login"),
  6. ]
  7. @app.route("/login", methods=["POST"])
  8. def register():
  9. """I'm registering a new user & returning a token!"""
  10. return jsonify({
  11. "token": jwt_routes.create_token(entity_id=1, table_name='users')
  12. })
  13. @app.route("/your_resource", methods=["POST"])
  14. def login():
  15. """I'm authorized & updating my token!"""
  16. return jsonify({
  17. "token": jwt_routes.update_token(entity_id=1)
  18. })

*Warning: The table_name must be the same as your tablename or __tablename__ attribute’s value.
(With SqlAlchemy, you can define a __tablename__ attribute directly or else
the name is derived from your entity’s database table name).

Setting the Token Expire Duration

There are two ways to set the expire duration of the JWT.

from your app config

  1. # Set the token expire duration to 7 days
  2. app.config["JWT_EXPIRE_DAYS"] = 7

calling the set_exp

  1. # Set the token expire duration to 14 days
  2. jwt_routes = JwtRoutes()
  3. # jwt_routes.init_app( ...etc
  4. jwt_routes.set_exp(expire_days=14)

By default the expire duration is set to 30 days

Create & update Tokens on Routes

Create a new entity & return a new token

  1. @app.route("/register", methods=["POST"])
  2. def register():
  3. user_data = request.get_json()
  4. try:
  5. user = UserModel(**user_data)
  6. user.create_user() # your entity creation logic
  7. # Here we pass the id as a kwarg to `create_token`
  8. token: str = jwt_routes.create_token(entity_id=user.id, table_name="users")
  9. # Now we can return a new token!
  10. return {
  11. "message": "User successfully created.",
  12. "token": str(token), # casting is optional
  13. }, 200

Access entity on Flask’s global context

  1. from app import app, jwt_routes
  2. # Example uses Marshmallow to serialize entity object
  3. class EntitySchema(Schema):
  4. id = fields.Integer()
  5. name = fields.String()
  6. @app.route("/login", methods=["GET"])
  7. def login():
  8. user_data = g.get("users") # This is your SqlAlchemy `__tablename__` or the default name.
  9. try:
  10. user_dumped = UserSchema().dump(user_data)
  11. except ValidationError as _:
  12. return {
  13. "error": "User requested does not exist."
  14. }, 401
  15. return {
  16. "data": user_dumped,
  17. "token": jwt_routes.update_token(entity_id=user_data.id),
  18. }, 200

If you are handling a request with a token in the headers you can call::

  1. jwt_routes.update_token(entity_id=user_data.id)

If you are handling a request without a token in the headers you can call::

  1. jwt_routes.create_token(entity_id=user_data.id, table_name="users")

An Example configuration for registering & logging in users of different types:

  1. app.config["IGNORED_ROUTES"] = [("GET", "/")]
  2. app.config["JWT_ROUTER_API_NAME"] = "/api/v1"
  3. app.config["WHITE_LIST_ROUTES"] = [
  4. ("POST", "/auth/user"), ("POST", "/auth/user/login"),
  5. ("POST", "/auth/teacher"), ("POST", "/auth/teacher/login"),
  6. ]
  7. # Optionally, you can pass your models to Flask's config:
  8. app.config["ENTITY_MODELS"] = [ UserModel, TeacherModel, ...etc ]

JSON Web Token setup

To send the JSON web token from your front end, you will need to pass a Bearer string in your authorization header.
For example:

  1. fetch(url, {
  2. headers: {
  3. Authorization: "Bearer <my_token>",
  4. }
  5. })

Routing without headers

If you require calling a resource without passing headers, then you can use the auth query param (useful when streaming video files):

  1. url = "http://example.com/cars?auth=my_token"

Google OAuth 2.0 Quick Start

Read the detailed instructions here: Flask-JWT-Router

  1. from flask_jwt_router import Google, JwtRoutes
  2. oauth_options = {
  3. "client_id": "<CLIENT_ID>",
  4. "client_secret": "<CLIENT_SECRET>",
  5. "redirect_uri": "http://localhost:3000",
  6. "tablename": "users",
  7. "email_field": "email",
  8. "expires_in": 3600,
  9. }
  10. jwt_routes = JwtRoutes()
  11. jwt_routes.init_app(
  12. app,
  13. google_oauth=oauth_options,
  14. strategies=[Google],
  15. entity_models=[MyModel],
  16. )

Google OAuth 2.0 with ReactJS

Flask-JWT-Router supports auth Google’s OAuth 2.0 Single Sign On strategy if you are using React only.
(We will provide Google’s OAuth 2.0 Single Sign On strategy for server to server as soon as possible!).

Quick Start

Create a login route for Google’s OAuth 2.0

  1. @app.route("/api/v1/google_login", methods=["POST"])
  2. def google_login():
  3. google = jwt_routes.get_strategy("Google")
  4. data = google.oauth_login(request)
  5. return data, 200

If your app requires multiple redirect uri’s then
you can use the redirect_uri kwarg to assign a uri for the current
request handler. For example:

  1. google = jwt_routes.get_strategy("Google")
  2. data = google.oauth_login(request, redirect="http://another_redirect.com")

We have created a ReactJS library specifically for Flask-JWT-Router - react-google-oauth2.0
In your React app directory install react-google-oauth2.0:

  1. npm install react-google-oauth2 --save

Testing

Testing OAuth2.0 in a Flask app is non-trivial, especially if you rely on Flask-JWT-Router
to append your user onto Flask’s global context (or g). Therefore we have provided a
utility method that returns a headers Dict that you can then use in your test view handler
request. This example is using the Pytest library:

  1. from flask_jwt_router import (
  2. BaseJwtRoutes,
  3. JwtRoutes,
  4. Google,
  5. GoogleTestUtil,
  6. TestRoutingMixin,
  7. )
  8. class TestJwtRoutes(TestRoutingMixin, BaseJwtRoutes):
  9. pass
  10. if not Config.E2E_TEST:
  11. jwt_routes = JwtRoutes()
  12. else:
  13. jwt_routes = TestJwtRoutes()
  14. if not config.E2E_TEST:
  15. jwt_routes.init_app(
  16. app,
  17. google_oauth=oauth_options,
  18. strategies=[Google],
  19. entity_models=[MyModel],
  20. )
  21. else:
  22. jwt_routes.init_app(
  23. app,
  24. google_oauth=oauth_options,
  25. strategies=[GoogleTestUtil],
  26. entity_models=[MyModel],
  27. )
  1. @pytest.fixture()
  2. def client():
  3. # See https://flask.palletsprojects.com/en/1.1.x/testing/ for details
  4. def test_blogs(client):
  5. google = jwt_routes.get_strategy("GoogleTestUtil")
  6. user_headers = google.create_test_headers(email="user@gmail.com")
  7. rv = client.get("/blogs", headers=user_headers)

If you are not running a db in your tests, then you can use the entity kwarg.
For example:

  1. # user is an instantiated SqlAlchemy object
  2. google = jwt_routes.get_strategy("GoogleTestUtil")
  3. user_headers = google.create_test_headers(email="user@gmail.com", entity=user)
  4. # user_headers: { "X-Auth-Token": "Bearer <GOOGLE_OAUTH2_TEST>" }

If you require more than one request to a Flask view handler in a single unit test, then set
the scope kwarg to application. (Default is function). If you are testing different
entities within a single unit test method or function then you must pass in your entity.
For example:

  1. my_entity = User(email="user@gmail.com") # If you're testing against a real db, make sure this is an entry in the db
  2. google = jwt_routes.get_strategy("GoogleTestUtil")
  3. _ = google.create_test_headers(email="user@gmail.com", scope="application", entity=my_entity)

Authors

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

Make sure you have Python versions: 3.6, 3.7, 3.8
Then run:

  1. tox

To check the docs look good locally you can run:

  1. make html

License

MIT