How to decode and validate access token in python?

I have an application registered in OKTA that uses PKCE flow. I used the guide available at https://developer.okta.com/docs/guides/implement-oauth-for-okta/request-access-token/ to get an access token and retrieved my jwk from https://{myoktadomain}/oauth2/v1/keys

Then, I tried to

    import jwt
    from jwt.algorithms import RSAAlgorithm

    # Key pulled from https://{myoktadomain}.oktapreview.com/oauth2/v1/keys
    key_json = '{"kty":"RSA","alg":"RS256","kid":"kid-value-here","use":"sig","e":"AQAB","n":"long-key-here"}'

    aud = "api://default"
    token_to_validate = "access-token-value-here"

    public_key = RSAAlgorithm.from_jwk(key_json)

    decoded = jwt.decode(token_to_validate, public_key, audience=aud, algorithms='RS256')

But I am getting the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/myuser/dev/projects/src/adminsvc/.tox/py37/lib/python3.7/site-packages/jwt/api_jwt.py", line 92, in decode
    jwt, key=key, algorithms=algorithms, options=options, **kwargs
  File "/Users/myuser/dev/projects/src/adminsvc/.tox/py37/lib/python3.7/site-packages/jwt/api_jws.py", line 156, in decode
    key, algorithms)
  File "/Users/myuser/dev/projects/src/adminsvc/.tox/py37/lib/python3.7/site-packages/jwt/api_jws.py", line 223, in _verify_signature
    raise InvalidSignatureError('Signature verification failed')
jwt.exceptions.InvalidSignatureError: Signature verification failed

I am not sure why I’m getting the InvalidSignatureError

Hi @mkhan! I see that you are using an Okta Org Authorization Server which means that it doesn’t have true access tokens, but rather opaque tokens; therefore will not have a valid key-id. This support page has more info on this distinction here https://support.okta.com/help/s/article/Signature-Validation-Failed-on-Access-Token?language=en_US.

According to this thread - Verify token signature, you shouldn’t need to validate access tokens from the Okta Org Authz Server.

Do you require access tokens to protect your APIs as described here https://support.okta.com/help/s/article/Difference-Between-Okta-as-An-Authorization-Server-vs-Custom-Authorization-Server?language=en_US? If yes, you may need to upgrade to our API Access Management feature.

Thanks, @sigama, That was very helpful insights. I created an authorization server and used it as the issuer URL and was able to decode and validate the token.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.