JwtRoutes API

Quick Start

Installation:

pip install flask-jwt-router

Basic Usage:

from flask import Flask
from flask_jwt_router import JwtRoutes

app = Flask(__name__)
# You are required to always set a unique SECRET_KEY for your app
app.config["SECRET_KEY"] = "your_app_secret_key"

JwtRoutes(app)

# If you're using the Flask factory pattern:
jwt_routes = JwtRoutes()

def create_app(config):
    ...
    jwt_routes.init_app(app)

Authorizing Routes

Define as a list of tuples:

app.config["WHITE_LIST_ROUTES"] = [
    ("POST", "/register"),
]

@app.route("/register", methods=["POST"])
def register():
    return "I don't need authorizing!"

Prefix your api name to whitelisted routes:

# All routes will
app.config["JWT_ROUTER_API_NAME"] = "/api/v1"
app.config["WHITE_LIST_ROUTES"] = [
    ("POST", "/register"),
]

@app.route("/api/v1/register", methods=["POST"])
def register():
    return "I don't need authorizing!"

Bypass Flask-JWT-Router on specified routes:

# Define homepage template routes for example on JWT_IGNORE_ROUTES
# & still get to use the api name on request handlers returning resources

app.config["IGNORED_ROUTES"] = [
    ("GET", "/")
]

Declare an entity model:

# Create your entity model (example uses Flask-SqlAlchemy)

class UserModel(db.Model):
    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

JwtRoutes(app, entity_models=[UserModel, TeacherModel, ...etc])

# Or pass later with `init_app`
def create_app(config):
    ...
    jwt_routes.init_app(app, entity_models=[UserModel, TeacherModel, ...etc])

Setting the Token Expire Duration

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

from your app config:

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

using the set_exp method:

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

By default the expire duration is set to 30 days

Authorization & Tokens

From your_app import jwt_routes:

# white list the routes
app.config["WHITE_LIST_ROUTES"] = [
    ("POST", "/register"),
    ("POST", "/login"),
]

@app.route("/register", methods=["POST"])
def register():
    # I'm registering a new user & returning a token!
    return jsonify({
        "token": jwt_routes.create_token(entity_id=1)
    })

@app.route("/login", methods=["POST"])
def login():
    # I'm authorized & updating my token!
    return jsonify({
        "token": jwt_routes.update_token(entity_id=1)
    })

Create a new entity & return a new token:

@app.route("/register", methods=["POST"])
def register():
    user_data = request.get_json()
    try:
        user = UserModel(**user_data)
        user.create_user() # your entity creation logic

        # Here we pass the id as a kwarg to `create_token`
        token: str = jwt_routes.create_token(entity_id=user.id, table_name="user")

        # Now we can return a new token!
        return {
            "message": "User successfully created.",
            "token": str(token),  # casting is optional
        }, 200

Access entity on Flask’s global context:

from app import app, jwt_routes

# Example uses Marshmallow to serialize entity object

@app.route("/login" methods=["GET"])
def login():
    user_data = g.get("entity")
    try:
        user_dumped = UserSchema().dump(user_data)
    except ValidationError as _:
       return {
                   "error": "User requested does not exist."
               }, 401
    return {
        "data": user_dumped,
        "token": jwt_routes.create_token(entity_id=user_data.id, table_name="user"),
    }, 200

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

jwt_routes.update_token(entity_id=user_data.id)

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

jwt_routes.create_token(entity_id=user_data.id, table_name="user")
class flask_jwt_router._jwt_routes.BaseJwtRoutes(app=None, **kwargs)[source]

If there app is None then self.init_app(app=None, **kwargs) need to be called inside the Flask app factory pattern. :param app: Flask application instance :param kwargs: entity_model

app = None

The Flask application instance.

config: flask_jwt_router._config.Config

The class that is used to create Config objects. See _config for more information.

create_token(**kwargs) → str[source]
Parameters

kwargs

Returns

str

encode_token(entity_id) → str[source]
Parameters

entity_id

Returns

entity: flask_jwt_router._entity.BaseEntity

The class that is used to create Entity objects. See _entity for more information.

entity_models: List[_GenericAlias]

A list of entity models

exp: int

Low level expire member. See _config & set with JWT_EXPIRE_DAYS or use set_exp.

get_app_config(app)[source]
Parameters

app – Flask Application Instance

Returns

Dict[str, Any]

get_entity_id(**kwargs)[source]
Parameters

kwargs – Dict[str, int]

Returns

str

get_strategy(name: str) → Optional[flask_jwt_router.oauth2._base.BaseOAuth][source]
Parameters

name – The name of the strategy

Returns

google_oauth: Dict

Optional. See google

init_app(app=None, **kwargs)[source]

You can use this to set up your config at runtime :param app: Flask application instance :return:

logger = <module 'logging' from '/home/docs/.pyenv/versions/3.7.9/lib/python3.7/logging/__init__.py'>

Logging.

routing: flask_jwt_router._routing.BaseRouting

The class that is used to create Routing objects. See _routing for more information.

set_exp(**kwargs) → None[source]
Parameters

kwargs – Dict[str, int] - expire_days: The expire time for the JWT in days

Returns

None

strategies: List[flask_jwt_router.oauth2._base.BaseOAuth]

Optional. A Lust of strategies to be implement in the routing

strategy_dict: Dict[str, flask_jwt_router.oauth2._base.BaseOAuth] = {}

List of instantiated strategies

update_token(**kwargs) → str[source]
Parameters

kwargs

Returns

str

class flask_jwt_router._jwt_routes.JwtRoutes(app=None, **kwargs)[source]