我正在尝试使用 django-rest-framework 在我的 Django REST API 中实现基于 Auth0 JWT 的身份验证。我知道有一个 JWT 库可用于 REST 框架,我尝试使用它,因为官方 Auth0 推特帐户提到它应该与 auth0 + Django 一起工作。
编辑:我正在使用 the official auth0 python api guide对于这段代码。它是为 Flask 编写的,但我认为我可以将它移植到 Django,因为它们的工作方式相似。
现在,这并没有达到我想要的效果,所以我正在尝试为 View 编写自己的 login_required
装饰器。我这里的代码如下:
def auth_required(f):
def wrap(request, *args, **kwargs):
auth = request.META.get('HTTP_AUTHORIZATION', None)
if not auth:
return authenticate({'code': 'authorization_header_missing', 'description': 'Authorization header is expected'})
parts = auth.split()
if parts[0].lower() != 'bearer':
return authenticate({'code': 'invalid_header', 'description': 'Authorization header must start with Bearer'})
elif len(parts) == 1:
return authenticate({'code': 'invalid_header', 'description': 'Token not found'})
elif len(parts) > 2:
return authenticate({'code': 'invalid_header', 'description': 'Authorization header must be Bearer + \s + token'})
token = parts[1]
try:
payload = jwt.decode(
token,
base64.b64decode(SECRET.replace("_","/").replace("-","+")),
audience=CLIENT_ID,
)
except jwt.ExpiredSignature:
return authenticate({'code': 'token_expired', 'description': 'token is expired'})
except jwt.InvalidAudienceError:
return authenticate({'code': 'invalid_audience', 'description': 'incorrect audience, expected: ' + CLIENT_ID})
except jwt.DecodeError:
return authenticate({'code': 'token_invalid_signature', 'description': 'token signature is invalid'})
return f(request, *args, **kwargs)
wrap.__doc__=f.__doc__
wrap.__name__=f.__name__
return wrap
现在,authenticate()
基本上是我对 Jsonify()
的自定义实现,用于 Python API 的 Auth0 文档中。我已经验证这有效,所以这不是问题。
SECRET
是我的 Auth0 密码,以 base64 编码(任何其他 key 都无法解码)
CLIENT_ID
是我的 Auth0 客户端 ID,根据 Auth0 文档,它用作受众。
我在前端使用 Angular 种子项目,我已经验证 token 确实随请求一起发送,并且我已经验证它与存储在 token< 中的 token 完全相同
后端变量。
当 jwt.decode()
被调用时,它每次都会触发 jwt.DecodeError
,我已经花了无数个小时试图解决这个问题,但我我对为什么这不有效感到非常震惊。我尝试将 JWT 选项设置为 false,特别是验证签名选项。这行得通,但我认为禁用 JWT 签名验证是不安全。
我不明白为什么这让我失望了,我已经尝试过同样的代码,但它没有在装饰器中,它做了同样的事情。装饰的 View 只是一个返回 OK HttpResponse 的空 View 。
长长的;使用 Django-REST + Auth0 JWT——无论我做什么,jwt.decode()
都不起作用。
EDIT2:值得一提的是,我是 django-rest 的 corsheaders
,它允许我发出跨域请求。我还按照 Auth0 的 Python API 指南底部的提示卸载并重新安装 JWT 库,但这对我没有任何帮助。
我是不是忽略了什么,这个实现是不是很不安全,或者你有什么更好的方法来用 Django 实现 Auth0?请让我知道,这个问题让我做噩梦。
最佳答案
“最难修复的错误通常是最愚蠢的错误”的经典案例...
我通过双击从 Auth0 仪表板复制了 key ,但没有意识到有些部分没有被复制。这修复了它。
如果需要,您可以在自己的项目中使用我的自定义装饰器来验证 JWT。
你导入它然后像这样使用它:
@auth_required
def myView(request):
....
关于python - Django + Auth0 JWT 认证拒绝解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34426066/