0

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():
     ...
linus
  • 399
  • 3
  • 19
  • Please always provide the full stacktrace of an error message you receive. If you don't bother to provide a minimal reproducible example, a traceback at least allows people to try and search through the code of the libraries involved. Refer to this page for additional guidelines on how to ask questions: https://stackoverflow.com/help/how-to-ask – Daniil Fajnberg Dec 07 '22 at 14:22

0 Answers0