Django + Auth0 JWT身份验证拒绝解码 [英] Django + Auth0 JWT authentication refusing to decode

查看:271
本文介绍了Django + Auth0 JWT身份验证拒绝解码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用django-rest-framework在我的Django REST API中实现基于Auth0 JWT的身份验证.我知道有一个适用于REST框架的JWT库,我已经尝试使用它,因为官方的Auth0 Twitter帐户提到它应该可以与auth0 + Django一起很好地工作.

I am trying to implement Auth0 JWT-based authentication in my Django REST API using the django-rest-framework. I know that there is a JWT library available for the REST framework, and I have tried using it because the official Auth0 twitter account mentioned that it should work well with auth0 + Django.

编辑:我正在为此代码使用官方auth0 python API指南 .它是为flask写的,但是我认为我可以将其移植到Django,因为它们的工作原理类似.

EDIT: I am using the official auth0 python api guide for this code. It's written for flask, but I figured I could just port it to Django seeing as they work similarly.

现在,这还没有达到我想要的效果,因此我正在尝试为视图编写自己的login_required装饰器.我在这里的代码如下:

Now, that didn't work out how I wanted to, so I am trying to write my own login_required decorater for a view. The code I have here is as following:

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文档中.我已经验证了这是可行的,所以这不是问题.

Now, the authenticate() is basically my custom implementation for Jsonify() which is used in the documentation of Auth0 for Python API's. I have verified that this works, so that's not a problem.

SECRET是我的Auth0机密,以base64编码(其他任何密钥均无法解码)
根据Auth0文档,CLIENT_ID是我的Auth0客户端ID,用作访问者.

SECRET is my Auth0 secret, encoded in base64 (any other keys failed to decode)
CLIENT_ID is my Auth0 client ID which is used as the audience, according to the Auth0 documentation.

我正在前端使用Angular种子项目,并且已经验证了令牌确实与请求一起发送,并且已经验证了与存储在token变量中的令牌完全相同.后端.

I am using the Angular seed project on the frontend-side, and I have verified that the token indeed gets sent with the request, and I have verified that it's the exact same token that gets stored in the token variable on the backend.

当调用jwt.decode()时,它将每次触发jwt.DecodeError,我花了无数小时试图解决此问题,但是对于为什么不是 ,我感到非常震惊.在职的.我尝试将JWT选项设置为false,特别是将验证签名设置为false.这行得通,但我认为禁用JWT签名的验证是不安全.

When jwt.decode() is called, it will trigger the jwt.DecodeError every time, and I have been spending countless hours trying to fix this, but I am absolutely stunned as to why this is not working. I have tried setting the JWT options to false, specifically the verify signature one. This worked, but I assume that it's unsafe to disable the verifying of the JWT signature.

我无法弄清楚为什么这会让我失望,我尝试了相同的代码,而没有将它放在装饰器中,并且它执行相同的操作.装饰的视图只是一个空视图,它返回一个确定的HttpResponse.

I cannot figure out why this is failing me, I have tried this same code without it being in a decorator and it does the same thing. The view which is decorated is just an empty view which returns an OK HttpResponse.

Tldr;无论我做什么,使用Django-REST + Auth0 JWT-jwt.decode()都不起作用.

Tldr; Using Django-REST + Auth0 JWT -- jwt.decode() will not work no matter what I do.

EDIT2 :值得一提的是,我对django-rest是corsheaders,这使我可以提出跨域请求.我还按照Auth0的Python API指南底部的提示来卸载并重新安装JWT库,但这对我无济于事.

EDIT2: It's worth mentioning I am corsheaders for django-rest which allows me to make cross-domain requests. I have also followed the tip at the bottom of the Python API guide from Auth0 to uninstall and reinstall the JWT library, but this did nothing for me.

我忽略了什么吗?此实现是完全不安全的还是您有使用Django实现Auth0的更好方法?请让我知道,这个问题正在引起我的噩梦.

Am I overlooking something, is this implementation plain unsecure or do you have any better way to implement Auth0 with Django? Please let me know, this problem is causing me nightmares.

推荐答案

最难修复的错误通常是最愚蠢的错误" ...

我通过双击从Auth0仪表板复制了密钥,但没有意识到有些部分没有被复制.这样就解决了.

I copied the secret key from the Auth0 dashboard by doubleclicking it, not realizing there were parts which didn't get copied. This fixed it.

如果需要,可以在自己的项目中使用我的自定义装饰器来验证JWT.

If you want, you can use my custom decorator in your own project, to verify the JWT's.

您导入它,然后像这样使用它:

You import it and then use it like so:

@auth_required
def myView(request):
    ....

这篇关于Django + Auth0 JWT身份验证拒绝解码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆