You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python解码JWT遇密钥数据反序列化失败问题(DRF+Auth0)

问题原因与解决方案

核心错误:JWT解码参数顺序错误

你在requires_scope装饰器里调用jwt.decode时,参数顺序写错了。PyJWT的jwt.decode函数中,第二个参数是key,而你把verify=False放在了这个位置,导致PyJWT将布尔值False当作密钥来解析,这直接引发了密钥格式错误的ValueError。

原错误代码:

decoded = jwt.decode(token, verify=False, algorithms=settings.AUTH0_ALGORITHMS)

修复方式1:修正参数顺序(不推荐,跳过验证有安全风险)

明确指定参数名,避免位置混淆:

decoded = jwt.decode(token, key=None, verify=False, algorithms=settings.AUTH0_ALGORITHMS)

修复方式2:复用已有的安全解码方法(推荐)

直接调用你已经写好的jwt_decode_token方法,这样既能验证令牌的合法性(避免伪造令牌绕过权限检查),又能正确获取scope:

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])
            try:
                decoded = jwt_decode_token(token)
            except Exception as e:
                response = JsonResponse({'message': 'Invalid or expired token'})
                response.status_code = 401
                return response
            
            if decoded.get("scope"):
                token_scopes = decoded["scope"].split()
                if required_scope in token_scopes:
                    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

额外优化建议

  1. 权限检查可以简化:用required_scope in token_scopes替代循环判断,代码更简洁高效。
  2. 增加异常捕获:调用jwt_decode_token时捕获异常,返回401(未授权)状态码,区分令牌无效和权限不足的情况。

内容的提问来源于stack exchange,提问作者Khubaib Khawar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 05:50:55