首页 > 解决方案 > 在python中使用PyJWT解码jwt令牌给出错误算法不支持

问题描述

我正在使用 PyJWT 解码来自 keycloak 的 JWT 令牌。

eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ6MWpiUExrTndMVTBkTHk3a0NIT1pyS2FJd3FPMXFrbThDeGtvVHg2QzFBIn0。eyJleHAiOjE2MjE0MjQwMjEsImlhdCI6MTYyMTQyMzk2MSwiYXV0aF90aW1lIjoxNjIxNDIxNzc0LCJqdGkiOiIwYzY2Y2I0My1lMGY1LTQzNjItYTc2MS1lN2M2OWVhNDM5MjUiLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjgwODAvYXV0aC9yZWFsbXMvbWFzdGVyIiwiYXVkIjpbIm1hc3Rlci1yZWFsbSIsImFjY291bnQiXSwic3ViIjoiN2Y2ODBlN2MtZGM4Yy00ZGJiLWJiZDEtMTE0ZGJhYjA2Zjc1IiwidHlwIjoiQmVhcmVyIiwiYXpwIjoiYW11bmRzZW4tZnJvbnRlbmQiLCJzZXNzaW9uX3N0YXRlIjoiYTM5YzJlNmUtZGNjMS00OTM5LTg0ODItYzk2NGE5ODMxNmYyIiwiYWNyIjoiMSIsImFsbG93ZWQtb3JpZ2lucyI6WyJodHRwOi8vbG9jYWxob3N0OjUwMDAiLCJsb2NhbGhvc3Q6NTAwMCJdLCJyZWFsbV9hY2Nlc3MiOnsicm9sZXMiOlsiY3JlYXRlLXJlYWxtIiwib2ZmbGluZV9hY2Nlc3MiLCJhZG1pbiIsInVtYV9hdXRob3JpemF0aW9uIl19LCJyZXNvdXJjZV9hY2Nlc3MiOnsibWFzdGVyLXJlYWxtIjp7InJvbGVzIjpbInZpZXctcmVhbG0iLCJ2aWV3LWlkZW50aXR5LXByb3ZpZGVycyIsIm1hbmFnZS1pZGVudGl0eS1wcm92aWRlcnMiLCJpbXBlcnNvbmF0aW9uIiwiY3JlYXRlLWNsaWVudCIsIm1hbmFnZS11c2VycyIsInF1.aksSjBU5hJ1rtn43NtbMt8E6gaGmJXDrtGDI7j0T7eo6PAcnUxG4spYNNhyksXVr3ZFvua2WyTKnZirqaJUI3zzdLj-XkE7zYCYWoJpjXITmmlj5oszD3pcRdGeyUVyQV49tIiUfUFi1KoIt9K016mH2s_beFrN3TYSjuLh5Epdk_dpNBh9YE_1f3opwsEbN2Jgz_j-VB6cQHq17RzWQIVSd6ZvftAWDWdc6nobOvTy1mZAA_DgsXwdjuNc8Qv36ztuDzkT-raCnuLH479ciBOFQZ0946obIE4ddJKpr7lnVupcbQZ6lDM_QZHz1hwkYqgSU-Ui8NHaWlqt4HJ5-9A

我的代码

import jwt
import traceback


try:
    public_key = """-----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhlOIQLHXwZoS3w9SBtvZ1ea4ftWmWnP+HCwlvs7XoJ9EhS+ZQEP7Z25tjW3I8mjUVL0XETrOOjQsD8O2nRBqizJsRaB8L9xsXdJmPHVTx7nphaBPtY5YHxxYqpwEC5rAKtx54YJxw6Ggeicmv+xXtaaDf/VALh5xxpa1U6yP5oqk3yV27yA0beQFVsdugkcfYN0C2FldaUcF9yTUf/KNHTYSu3Ar7iN9U+qEHwaznrLShwh7iknldTKTgEw3liHL8K/5ZlqxHPsL02InwZMaIRic3zNIgVvwedroM6nqZBB4mi1+T0dZn4qsNkG4D0w7IE7MTRgyyYARqrGEq5yOFwIDAQAB
    -----END PUBLIC KEY-----"""

    secret_key = "base-flask-oidc-secret-key"
    token = "eyJhbGciOiJSUzI1NiIsInR5cCIgOiAiSldUIiwia2lkIiA6ICJ6MWpiUExrTndMVTBkTHk3a0NIT1pyS2FJd3FPMXFrbThDeGtvVHg2QzFBIn0.eyJleHAiOjE2MjE0MjQwMjEsImlhdCI6MTYyMTQyMzk2MSwiYXV0aF90aW1lIjoxNjIxNDIxNzc0LCJqdGkiOiIwYzY2Y2I0My1lMGY1LTQzNjItYTc2MS1lN2M2OWVhNDM5Mj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MiLCJ2aWV3LXByb2ZpbGUiXX19LCJzY29wZSI6Im9wZW5pZCBwcm9maWxlIGVtYWlsIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJuYW1lIjoiYWRtaW5maXJzdCBhZG1pbmxhc3QiLCJwcmVmZXJyZWRfdXNlcm5hbWUiOiJhZG1pbiIsImdpdmVuX25hbWUiOiJhZG1pbmZpcnN0IiwiZmFtaWx5X25hbWUiOiJhZG1pbmxhc3QiLCJlbWFpbCI6ImFkbWludGVzdEBnbWFpbC5jb20ifQ.aksSjBU5hJ1rtn43NtbMt8E6gaGmJXDrtGDI7j0T7eo6PAcnUxG4spYNNhyksXVr3ZFvua2WyTKnZirqaJUI3zzdLj-XkE7zYCYWoJpjXITmmlj5oszD3pcRdGeyUVyQV49tIiUfUFi1KoIt9K016mH2s_beFrN3TYSjuLh5Epdk_dpNBh9YE_1f3opwsEbN2Jgz_j-VB6cQHq17RzWQIVSd6ZvftAWDWdc6nobOvTy1mZAA_DgsXwdjuNc8Qv36ztuDzkT-raCnuLH479ciBOFQZ0946obIE4ddJKpr7lnVupcbQZ6lDM_QZHz1hwkYqgSU-Ui8NHaWlqt4HJ5-9A"
    # token_json = jwt.decode(token, secret_key, algorithms=['HS256', 'RS256'], audience='account')
    token_json = jwt.decode(token, public_key, algorithms=['HS256', 'RS256'], audience='account')
    print(access_token_json)
    
except Exception:
    print(traceback.print_exc())

根据jwt.io,它显示标题

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "z1jbPLkNwLU0dLy7kCHOZrKaIwqO1qkm8CxkoTx6C1A"
}

我尝试使用公钥和密钥,两者都给我错误

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jws.py", line 232, in _verify_signature
    alg_obj = self._algorithms[alg]
KeyError: 'RS256'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "jwt_test.py", line 16, in <module>
    access_token_json = jwt.decode(access_token, public_key, algorithms=['HS256', 'RS256'], audience='account')
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jwt.py", line 119, in decode
    decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jwt.py", line 95, in decode_complete
    **kwargs,
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jws.py", line 149, in decode_complete
    self._verify_signature(signing_input, header, signature, key, algorithms)
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jws.py", line 239, in _verify_signature
    raise InvalidAlgorithmError("Algorithm not supported")
jwt.exceptions.InvalidAlgorithmError: Algorithm not supported

如果我要从算法列表中删除“RS256”。

token_json = jwt.decode(token, public_key, algorithms=['HS256'], audience='account')

然后我得到错误。

Traceback (most recent call last):
  File "jwt_test.py", line 18, in <module>
    token_json = jwt.decode(token, public_key, algorithms=['HS256'], audience='account')
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jwt.py", line 119, in decode
    decoded = self.decode_complete(jwt, key, algorithms, options, **kwargs)
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jwt.py", line 95, in decode_complete
    **kwargs,
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jws.py", line 149, in decode_complete
    self._verify_signature(signing_input, header, signature, key, algorithms)
  File "/usr/local/lib/python3.7/site-packages/jwt/api_jws.py", line 229, in _verify_signature
    raise InvalidAlgorithmError("The specified alg value is not allowed")

我该如何解决这个问题。

提前致谢!

################### 回答 #######################

我能够通过

按照@KlausD 在评论中的建议安装密码学

pip install cryptography

并将公钥更改为

public_key = """-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAhlOIQLHXwZoS3w9SBtvZ1ea4ftWmWnP+HCwlvs7XoJ9EhS+ZQEP7Z25tjW3I8mjUVL0XETrOOjQsD8O2nRBqizJsRaB8L9xsXdJmPHVTx7nphaBPtY5YHxxYqpwEC5rAKtx54YJxw6Ggeicmv+xXtaaDf/VALh5xxpa1U6yP5oqk3yV27yA0beQFVsdugkcfYN0C2FldaUcF9yTUf/KNHTYSu3Ar7iN9U+qEHwaznrLShwh7iknldTKTgEw3liHL8K/5ZlqxHPsL02InwZMaIRic3zNIgVvwedroM6nqZBB4mi1+T0dZn4qsNkG4D0w7IE7MTRgyyYARqrGEq5yOFwIDAQAB\n-----END PUBLIC KEY-----"""

标签: pythonjwtkeycloakpyjwt

解决方案


再次阅读PyJWT 安装指南后,似乎对于某些签名算法,如RSA,需要安装python 密码库。

我通过安装依赖解决了这个问题:

pip install pyjwt[crypto]

推荐阅读