我正在使用authlib库来解码 JWT 令牌。
当我按原样运行时,此代码工作正常。
from authlib.specs.rfc7519 import jwt
encoded_jwt = '''eyJ0eXAiOiJKV1Qi.....'''
secret = b'''-----BEGIN PUBLIC KEY-----
.....
-----END PUBLIC KEY-----'''
claims = jwt.decode(encoded_jwt, secret)
print(type(claims))
import json
json_parse = json.loads(json.dumps(claims))
email = json_parse['http://wso2.org/claims/emailaddress']
print(email)
roles = json_parse['http://wso2.org/claims/role']
print(roles)
email, roles[-1]
但是当我将它添加到函数中时它不起作用。通过这个问题,我无法在 FLASK 框架中使用它。下面的代码不起作用。请不要回答检查公钥,因为它在上面的代码中工作正常。
def getsessions():
from authlib.specs.rfc7519 import jwt
encoded_jwt = '''eyJ0eXAiOiJ....'''
secret = b'''-----BEGIN PUBLIC KEY-----
............
-----END PUBLIC KEY-----'''
claims = jwt.decode(encoded_jwt, secret)
print(type(claims))
import json
json_parse = json.loads(json.dumps(claims))
email = json_parse['http://wso2.org/claims/emailaddress']
print(email)
roles = json_parse['http://wso2.org/claims/role']
print(roles)
email, roles[-1]
email,role=getsessions()
print(email)
我得到的错误是:
回溯(最近一次通话最后):文件“/home/sathyakugan/PycharmProjects/JWTsample/ss.py”,第 50 行,在电子邮件中,role=getsessions() 文件“/home/sathyakugan/PycharmProjects/JWTsample/ss.py” ,第 39 行,在 getsessions 声明中 = jwt.decode(encoded_jwt, secret) 文件“/home/sathiyakugan/PycharmProjects/Python/venv/lib/python3.5/site-packages/authlib/specs/rfc7519/jwt.py”,第 119 行,在 decode data = self._jws.deserialize_compact(s, key_func, decode_payload) File "/home/sathiyakugan/PycharmProjects/Python/venv/lib/python3.5/site-packages/authlib/specs/rfc7515/jws. py”,第 108 行,在 deserialize_compact self._algorithms、jws_header、payload、key)文件“/home/sathiyakugan/PycharmProjects/Python/venv/lib/python3.5/site-packages/authlib/specs/rfc7515/util.py ",第 14 行,在 prepare_algorithm_key key = algorithm.prepare_public_key(key) 文件“/home/sathiyakugan/PycharmProjects/Python/venv/lib/python3.5/site-packages/authlib/specs/rfc7518/_backends/_key_cryptography.py”中,行28、在prepare_public_key return load_pem_public_key(key, backend=default_backend()) 文件“/home/sathiyakugan/PycharmProjects/Python/venv/lib/python3.5/site-packages/cryptography/hazmat/primitives/serialization.py”中,行24、在load_pem_public_key返回backend.load_pem_public_key(data)文件“/home/sathiyakugan/PycharmProjects/Python/venv/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/backend.py”,第1040行,在 load_pem_public_key self._handle_key_loading_error() 文件“/home/sathiyakugan/PycharmProjects/Python/venv/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/backend.py”,第 1291 行,在 _handle_key_loading_error 中引发 ValueError(“无法反序列化密钥数据。”) ValueError:无法反序列化密钥数据。
请帮助我哪里出错了。我一直在努力解决这个问题 2 天。请帮忙。