Last Updated: August 21, 2017
·
1.449K
· 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)

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

A JWT stored where page scripts can read it is visible to every library on that page. An injected script does not need to forge the signature. It can copy the token and reuse it.

Security insights from Cside