Last Updated: August 21, 2017
·
1.041K
· moonflock

Flask JWT optional authentication

The problem is when using Flask-JWT the currentidentity is not push to the context stack which means that even the user passes a token the currentidentity is None, you can fix this using this decorator

from flask_jwt import _jwt
from flask import _request_ctx_stack
from functools import wraps
import jwt

def jwt_optional(realm=None):
    def wrapper(fn):
        @wraps(fn)
        def decorator(*args, **kwargs):
            token = _jwt.request_callback()
            try:
                payload = _jwt.jwt_decode_callback(token)
            except jwt.exceptions.DecodeError:
                pass
            else:
                _request_ctx_stack.top.current_identity = _jwt.identity_callback(payload)
            return fn(*args, **kwargs)
        return decorator
    return wrapper

or even better, register a callback to before request

@app.before_request
def push_to_ctx():
    token = _jwt.request_callback()
    try:
        payload = _jwt.jwt_decode_callback(token)
    except jwt.exceptions.DecodeError:
        pass
    else:
        _request_ctx_stack.top.current_identity = _jwt.identity_callback(payload)