AuthLib and Azure Active Directory: Can I change the claim name that authlib expects for scope?

100 Views Asked by At

I'm writing a Flask API and implementing authorization using authlib. The auth flow is OAuth Auth Code Grant with PKCE flow where my auth server is Azure Active Directory. Authlib is currently throwing a "insufficient_scope" and I think that's because AuthLib expects the scope to be in a claim named "scope" where AAD puts the scope in a claim named "scp". Is there a way to change the expected scope?

The following code is a workaround where I specify an expected "scp" claim, but it results in a "invalid_token" rather than an "insufficient_scope" so I'm wondering if there's a better solution? I went through authlib docs and can't find a better solution.

class AADTokenValidator(JWTBearerTokenValidator):
    def __init__(self):
        issuer = f"https://sts.windows.net/{CLIENT_ID}/"

        keys_response = requests.get(
            f"https://login.microsoftonline.com/{CLIENT_ID}/discovery/v2.0/keys").json()

        public_key = JsonWebKey.import_key_set(keys_response)
        super(AADTokenValidator, self).__init__(
            public_key
        )
        self.claims_options = {
            "exp": {"essential": True},
            "aud": {"essential": True, "value": AUDIENCE},
            "iss": {"essential": True, "value": issuer},
            "scp": {"essential": True, "value": SCOPE},
        }


require_auth = ResourceProtector()

require_auth.register_token_validator(
    AADTokenValidator())

@app.route('/do-something', methods=['POST'])
@require_auth(None)
def do_something():

0

There are 0 best solutions below