首页 > 解决方案 > Django Rest 框架 JWT 身份验证

问题描述

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

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

设置.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 进行了测试,但我得到了同样的错误。不确定标题格式是否有错误,或者我是否缺少其他东西。任何帮助将不胜感激!

在此处输入图像描述

编辑:我已将设置更改为

'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."

标签: django-rest-frameworkjwt

解决方案


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

AUTH_USER_MODEL = 'main.User'


推荐阅读