在Python中解码JWT时无法反序列化密钥数据



我在DRF项目中使用Auth0生成令牌并进行身份验证。如果我正常地对令牌进行编码和解码,一切都很好。但我已经编写了一个方法requires_scope,该方法确定任何API是否需要所需的范围(API上的decorator告诉(。方法如下:

def requires_scope(required_scope):
"""Determines if the required scope is present in the Access Token
Args:
required_scope (str): The scope required to access the resource
"""
def require_scope(f):
@wraps(f)
def decorated(*args, **kwargs):
token = get_token_auth_header(args[0])
decoded = jwt.decode(token, verify=False, algorithms=settings.AUTH0_ALGORITHMS)
if decoded.get("scope"):
token_scopes = decoded["scope"].split()
for token_scope in token_scopes:
if token_scope == required_scope:
return f(*args, **kwargs)
response = JsonResponse({'message': 'You don't have access to this resource'})
response.status_code = 403
return response
return decorated
return require_scope

现在,当我对任何特定的作用域使用API上的decorator时,它不会解码JWT,并显示以下ValueError错误:

('Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).', [_OpenSSLErrorWithText(code=75497580, lib=9, reason=108, reason_text=b'error:0480006C:PEM routines::no start line')])

这是我的解码方法:

def jwt_decode_token(token):
header = jwt.get_unverified_header(token)
jwks = requests.get('https://{}/.well-known/jwks.json'.format(settings.SOCIAL_AUTH_AUTH0_DOMAIN)).json()
public_key = None
for jwk in jwks['keys']:
if jwk['kid'] == header['kid']:
public_key = jwt.algorithms.RSAAlgorithm.from_jwk(json.dumps(jwk))
# public_key = "-----BEGIN PUBLIC KEY-----n" + jwk['x5c'][0] + "n-----END PUBLIC KEY-----n"
# print(public_key)
if public_key is None:
raise Exception('Public key not found.')
issuer = 'https://{}/'.format(settings.SOCIAL_AUTH_AUTH0_DOMAIN)
return jwt.decode(
token,
public_key,
audience=settings.AUTH0_TOKEN_API_AUDIENCE,
issuer=issuer,
algorithms=['RS256']
)

这是我传递给API调用的有效载荷(它包含作用域(:

payload = f"{{"client_id":"{settings.SOCIAL_AUTH_AUTH0_KEY}",
"client_secret":"{settings.SOCIAL_AUTH_AUTH0_SECRET}",
"audience":"{settings.AUTH0_TOKEN_API_AUDIENCE}",
"grant_type":"password",
"username":"{email}",
"password":"{password}",
"scope":"read:messages"}}"

我怎么了?有人能帮忙吗?

它之所以抱怨密钥,是因为它仍在尝试进行验证。为了使用pyjwt正确禁用此功能,请执行以下操作:

jwt.decode(token, algorithms=["RS256"], options={"verify_signature": False})

请参阅pyjwt文档(有趣的是,我不能跳过算法块(:https://pyjwt.readthedocs.io/en/latest/usage.html#reading-未经验证的索赔集

最新更新