I am using flask_oidc to verify the access token sent from the client.
To check if the token is valid, I can use from flask_oidc:
@oidc.accept_token(require_token=True)
However, I also need to check the roles claim in the token. To accomplish this, I think I need to write my own function.
So this is my custom decorator:
from flask import g, jsonify
from functools import wraps
def authorize(func):
@wraps(func)
def wrapper(role_required, *args, **kwargs):
user_id = g.oidc_token_info['sub']
user_roles = g.oidc_token_info['resource_access']['zkl-api']['roles']
# check if user is authorized
if role_required not in user_roles:
return jsonify({"message": "Not authorized"}), status.HTTP_401_UNAUTHORIZED
else:
print('authorized')
return func(user_id, *args, **kwargs)
return wrapper
Unfortunately, I get the following error message:
RuntimeError: Working outside of application context.
The error occurs on this line:
user_id = g.oidc_token_info['sub']
Here, I am trying to fetch token claims using 'g' object from inside the function.
Does anyone know where my mistake is?
For completeness, below is how I invoke the decorator function from my endpoint:
@app.route('/', methods=['GET'])
@oidc.accept_token(require_token=True) # <-- here I am using flask_oidc built-in decorator to check if token is valid
@authorize('reader') # <-- here I am passing the role 'reader' to my custom decorator
def get_areas():
...