marcospereirampj / python-keycloak

MIT License
685 stars 294 forks source link

Token decode gives error 'Invalid audience' #89

Open saivisal1 opened 4 years ago

saivisal1 commented 4 years ago

I am trying to decode the token using token_info = keycloak_openid.decode_token(token['access_token'], key=KEYCLOAK_PUBLIC_KEY, options=options)

_KEYCLOAK_PUBLIC_KEY_ -----BEGIN PUBLIC KEY-----\n xxxx xxxx \n-----END PUBLIC KEY-----

options {'exp': True, 'verify_signature': False, 'verify_aud': True}

Error `token_info = keycloak_openid.decode_token(token['access_token'], key=KEYCLOAK_PUBLIC_KEY, options=options)

Traceback (most recent call last): File "", line 1, in File "/venv/lib/python3.5/site-packages/keycloak/keycloak_openid.py", line 346, in decode_token audience=self.client_id, **kwargs) File "/venv/lib/python3.5/site-packages/jose/jwt.py", line 172, in decode options=defaults) File "/venv/lib/python3.5/site-packages/jose/jwt.py", line 495, in _validate_claims _validate_aud(claims, audience=audience) File "/venv/lib/python3.5/site-packages/jose/jwt.py", line 357, in _validate_aud raise JWTClaimsError('Invalid audience') jose.exceptions.JWTClaimsError: Invalid audience `

simonrankine commented 3 years ago

I hit this - it looks like there has been a change to KeyCloak recently, and it doesn't map the client ID into the auth field of the token by default any more. The solution for me was to add a mapper that maps the client ID into the audience claim (more here: https://stackoverflow.com/questions/53550321/keycloak-gatekeeper-aud-claim-and-client-id-do-not-match)

MohiuddinSumon commented 3 years ago

I also faced similar issue today, I passed the audience with decode call

lucj commented 3 years ago

@MohiuddinSumon would you have an example on own to provide the audience in the decode call ?

MohiuddinSumon commented 3 years ago

@lucj what I finally ended up doing was something like this:

options = {"verify_signature": True, "verify_aud": False, "exp": True}
        return keycloak_instance.decode_token(given_token, key=given_key, options=options)

setting verify_aud false was sufficient for my case

lucj commented 3 years ago

Thanks @MohiuddinSumon I'm using the same.

woprandi commented 1 year ago

same issue with latest keycloak

0xf938Ac9BA commented 1 year ago

same issue with latest keycloak

Have you managed to solve it?

woprandi commented 1 year ago

same issue with latest keycloak

Have you managed to solve it?

Yes few weeks ago :

I added a token mapper (with type Audience) to the dedicated scope of my client. Clients > Your client > Client scopes > your-client-dedicated > Add mapper > by configuration > Audience. Add a name of the mapper, select your client on the select box and enable "Add to access token". Your client should now be in the "aud" field of the access token

0xf938Ac9BA commented 1 year ago

Thank you!