我正在尝试使用公钥解码Gravitee令牌。我已经测试了PyJWT、authlib、python和jwcrypto库,并查看了这个页面上的许多帖子,但是我在所有这些文章中都得到了相同的错误,我无法修复这个问题。
错误:
(‘无法反序列化密钥数据。该数据可能格式不正确,可能使用不支持的算法加密,也可能是不支持的密钥类型(例如,带有显式参数的EC曲线)。’,_OpenSSLErrorWithText(code=151584876,lib=9,reason=108,R理性_text=b‘’error:0909006C:PEM routines:get_name:no开始行‘)
根据Gravitee的说明,我获得了公钥的第一位:
https://jwt.io提供的关于我的令牌的一些信息:
HEADER:ALGORITHM & TOKEN TYPE
{
"kid": "default",
"alg": "RS256"
}Python打包版本:
PyJWT==2.3.0 (也用2.1.0测试)
cryptography==36.0.0 (一些帖子是必需的)
我的代码:
from rest_framework import permissions
from rest_framework.exceptions import APIException
from django.conf import settings
import jwt
class TokenNotValid(APIException):
status_code = 403
default_detail = "Invalid or absent JWT token field."
class NoAuthHeader(APIException):
status_code = 403
default_detail = "Absent 'Authorization' header."
class ValidJWTPermission(permissions.BasePermission):
"""
Global permission check for JWT token.
"""
def _get_pubkey(self):
key = """-----BEGIN PUBLIC KEY-----\n""" + settings.GRAVITEE_PUBLIC_KEY + """\n-----END PUBLIC KEY-----"""
return key
def has_permission(self, request, view):
auth_header = request.META.get('HTTP_AUTHORIZATION')
# print("Received header:")
# print(auth_header)
if auth_header is None:
raise NoAuthHeader
try:
token = auth_header.split()[1]
# print("Encoded Token:")
# print(token)
public_key = self._get_pubkey()
print(public_key)
claims = jwt.decode(token, key=public_key, algorithms=['RS256'])
claims.validate()
except Exception as e:
print(e)
raise TokenNotValid
# print("Decoded token:")
# print(dec_token)
return True我还测试了像key.encode()和key.encode('ascii')这样的密钥编码,或者用"BEGIN RSA公共密钥“来编写密钥,而不是"BEGIN公钥”,任何东西都对我有效。我总是犯同样的错误。
发布于 2021-12-02 10:28:12
根据库的不同,您通常需要JWK格式的密钥,如以下链接所示:https://demo.identityserver.io/.well-known/openid-configuration/jwks
当您处理令牌时,这个JSON Web密钥(JWK)格式是表示密钥的标准,也许您的库也想要这种格式的密钥?
https://stackoverflow.com/questions/70187977
复制相似问题