Django Rest Framework JWT身份验证

时间:2018-09-26 08:00:35

标签: django-rest-framework jwt

我在登录JWT后发布/获取任何请求时遇到问题。 (我正在使用 djangorestframework-jwt 库)用户成功登录,应用程序返回json令牌,但是当我将此令牌用于下一个收到的请求时

{
    "detail": "Authentication credentials were not provided."
}

settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_ALLOW_REFRESH': True,
    'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1),
    'JWT_REFRESH_EXPIRATION_DELTA': datetime.timedelta(days=7),
}

登录视图

def post(self, request, format=None):

    if not request.data:
        return Response({'Error': "Please provide username/password"},  status=status.HTTP_400_BAD_REQUEST)

    username = request.data['username']
    password = request.data['password']

    try:
        user = User.objects.get(email=username, password=password)
    except User.DoesNotExist:
        return Response({'Error': "Invalid username/password"}, status=status.HTTP_400_BAD_REQUEST)

    if user:
        payload = {
            'id': user.id,
            'email': user.email,
            'first_name': user.first_name
        }

        jwt_token = jwt.encode(payload, "SECRET_KEY")  # to be changed

        return Response({'token': jwt_token}, status=status.HTTP_200_OK)

,然后每个其他视图都包含

 authentication_class = (JSONWebTokenAuthentication,)
 permission_classes = (IsAuthenticated,)

我已经对邮递员和curl进行了测试,但是得到了相同的错误。不知道标题格式是否有错误,或者是否还有我遗漏的其他内容。任何帮助将不胜感激!

enter image description here

编辑: 我已将设置更改为

'DEFAULT_AUTHENTICATION_CLASSES': (
    'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.BasicAuthentication',
),

但现在我明白了

{
    "detail": "Error decoding signature."
}

编辑:我认为问题是jwt_token = jwt.encode(payload, 'SECRET_KEY')可能返回无法识别的令牌...如果我使用obtain_jwt_token生成的令牌,那么我可以查询任何端点。有人可以解释吗?

编辑:因此我更改为jwt_token = jwt_encode_handler(payload),并且设置文件包含JWT_SECRET_KEY(当我验证登录jwt后收到的令牌时,它的确是具有正确有效负载和机密的正确令牌。 ),但仍无法识别"detail": "Invalid signature."

2 个答案:

答案 0 :(得分:0)

我设法解决了我的问题。在对用户进行身份验证时,我正在检查我之前创建的自定义user表,该表与django的auth_user表不同。我将django的设置更改为使用我的自定义用户表,然后使用身份验证中的令牌处理其他请求。

AUTH_USER_MODEL = 'main.User'

答案 1 :(得分:-1)

问题是您使用“ SECRET KEY”对JWT进行编码,然后使用另一个密钥对JWT进行解码。 jwt使用的默认密钥是settings.SECRET_KEY。但是,当您创建自定义jwt令牌时,会使用字符串作为机密“ SECRET_KEY”。但是您使用默认的jwt验证,该验证自动使用settings.SECRET_KEY。 因此,将d3.xml("/picture.svg").mimeType("image/svg+xml").get((error, xml) => { d3.select(".parent .parent__items") .selectAll(".parent-item .parent__inner-item .parent__svg") .attr("element-type", "a") .each(function (d, i){ d3.select(this).node().append(xml.documentElement.cloneNode(true)); }); }); 添加到您的JWT设置中,并使用此密钥进行编码和解码。 例如:

'JWT_SECRET_KEY': settings.SECRET_KEY,

或者您可以覆盖jwt验证并创建自己的验证。