PyJWT will not decode a Keycloak or RS256 token: algorithm errors
jwt.exceptions.InvalidAlgorithmErrorShort answer
RS256 and ES256 need the cryptography package, and jwt.decode only accepts the algorithms you list. Install pyjwt[crypto], pass algorithms=[...] matching the token's alg header, and catch jwt.InvalidTokenError, the base class for every invalid-token failure.
Fix it fast
1Find out which cause you have
Read the token's header without verifying anything, to see which alg and kid it declares.
python -c "import jwt,sys; print(jwt.get_unverified_header(sys.argv[1]))" "$TOKEN"2Match what you see, then jump to its fix
- 1
The token header says RS256 or ES256, and the error mentions a missing dependencyThe cryptography package is not installedFix - 2
jwt.decode(token, key, algorithms=["HS256"]) on a token whose header says RS256The algorithms list does not contain the token's algFix - 3
Keycloak or another provider signs with RS256, but you passed the client secret as a stringThe key is the wrong kind for the algorithmFix - 4
You want one except clause for every failed decodeCatching the right exception for any invalid tokenFix
- 1
What does the error look like?
jwt.exceptions.InvalidAlgorithmErrorjwt.exceptions.MissingCryptographyErrorDecodeError
Cause 1 of 4
The cryptography package is not installed
1Check
PyJWT says RSA and ECDSA algorithms need the cryptography library, and RSA decoding requires that module.
pip show cryptography pyjwt2Fix
Install PyJWT with the crypto extra, which PyJWT recommends for requirements files.
pip install "pyjwt[crypto]"3Verify
Decode again; the missing-dependency error is gone.
python -c "import jwt; print(jwt.__version__)"Confirmed by pyjwt.readthedocs.io
Cause 2 of 4
The algorithms list does not contain the token's alg
1Check
decode only accepts tokens whose alg header is in the algorithms list you pass; otherwise it rejects the token with InvalidAlgorithmError. Since PyJWT 2.0 the list is required.
python -c "import jwt,sys; print(jwt.get_unverified_header(sys.argv[1])['alg'])" "$TOKEN"2Fix
Hard-code the algorithm your provider signs with, next to where you configure the key. Do not build the list from the token's own header.
data = jwt.decode(token, signing_key, algorithms=["RS256"], audience="my-api")3Verify
The claims come back as a dict.
python decode_test.pyConfirmed by pyjwt.readthedocs.io
Cause 3 of 4
The key is the wrong kind for the algorithm
1Check
RS256 needs the provider's RSA public key. A shared secret only works with HMAC algorithms such as HS256.
python -c "import jwt,sys; print(jwt.get_unverified_header(sys.argv[1]))" "$TOKEN"2Fix
Fetch the signing key from the provider's JWKS endpoint; PyJWKClient picks the right one by the token's kid.
from jwt import PyJWKClient
client = PyJWKClient("https://keycloak.example.com/realms/demo/protocol/openid-connect/certs")
signing_key = client.get_signing_key_from_jwt(token)
data = jwt.decode(token, signing_key, algorithms=["RS256"], audience="account")3Verify
Decode a token issued a minute ago.
python decode_test.pyConfirmed by pyjwt.readthedocs.io
Cause 4 of 4
Catching the right exception for any invalid token
1Check
InvalidTokenError is the base exception when decode fails on a token. DecodeError, InvalidSignatureError, ExpiredSignatureError and InvalidAlgorithmError all inherit from it. InvalidKeyError and PyJWKClientError do not; they inherit from PyJWTError.
python -c "import jwt; print(jwt.InvalidTokenError.__mro__)"2Fix
Catch InvalidTokenError for bad tokens, and PyJWTError if you also want key and JWKS errors.
try:
data = jwt.decode(token, signing_key, algorithms=["RS256"])
except jwt.ExpiredSignatureError:
... # ask the user to sign in again
except jwt.InvalidTokenError:
... # any other bad token: reject with 4013Verify
Send an expired token and a garbage token; both reach their own branch.
python decode_test.pyConfirmed by pyjwt.readthedocs.io
How do I stop it coming back?
- Install pyjwt[crypto] in requirements, not plain pyjwt, when you verify RS256 or ES256 tokens.
- Pin algorithms in code and fetch keys through PyJWKClient.
- Catch ExpiredSignatureError before the general InvalidTokenError.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- stegnor.comMy company site: 804 pages from a Python and Jinja generator, with 15 free browser tools.
- MenuloA restaurant discovery platform in Germany, kept current by a Python ingestion pipeline.
- ShopGoAn e-commerce aggregator with a Python scraping engine behind its catalog, past 10K Google Play downloads.
Related fixes
Security
PyJWT decode fails with ValueError: Could not deserialize key data
jwt.exceptions.InvalidKeyError
jwt.decode hands your key to the cryptography library, which must read it as PEM or SSH.
3 causes, each with a fixSecurity
Paramiko fails now and then with Error reading SSH protocol banner
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner
Paramiko opens the TCP connection, then waits a short time for the server to send its SSH banner.
2 causes, each with a fixSecurity
Paramiko key login fails after agreeing on rsa-sha2-512
paramiko.ssh_exception.AuthenticationException: Authentication failed.
Since Paramiko 2.9 an RSA key is signed with rsa-sha2-512 or rsa-sha2-256 instead of SHA-1.
2 causes, each with a fixSecurity
Python rejects a self-signed certificate in the chain
certificate verify failed: self signed certificate in certificate chain (_ssl.c:992)
Python could not build a trusted path from the server certificate to a root it knows.
3 causes, each with a fixSecurity
Entra ID token request fails: the request body must contain the parameter 'grant_type'
AADSTS900144: The request body must contain the following parameter: 'grant_type'.
The token endpoint did not find grant_type in the form body of your POST.
3 causes, each with a fixSecurity
Angular HttpClient does not add the X-XSRF-TOKEN header to a request
403 Forbidden on POST, PUT or DELETE while GET works
Angular copies the XSRF-TOKEN cookie into an X-XSRF-TOKEN header only for mutating requests to the same origin, and only when the cookie is readable by script.
5 causes, each with a fix