【发布时间】:2023-02-18 05:25:10
【问题描述】:
我在我的 DRF 项目中使用 Auth0 来生成令牌并进行身份验证。如果我正常编码和解码令牌,一切正常。但是我写了一个方法requires_scope,它确定是否需要任何 API 的范围(API 上的装饰器告诉)。方法如下:
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 上为任何特定范围使用装饰器时,它不会解码 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\"}}"
我在做什么错?谁能帮忙?
【问题讨论】:
标签: python oauth jwt decode auth0