在 Django Rest Framework 中解码签名时出错

bys*_*eti 8 python django json jwt django-rest-framework

我在我的 API 中使用 JWT。但我无法使用 JWT 进行身份验证。我找不到什么问题。感谢您的帮助。

@api_view(['POST'])
@permission_classes((AllowAny,))
def UserLogin(request):
    try:
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        account = authenticate(username=username, password=password)

    except (User.DoesNotExist, User.PasswordDoesNotMatch):
            return Response({'message': 'Wrong credentials'}, status=400)
    if account is not None:
        if account.is_active:
            login(request, account)
            if request.user.is_superuser:
                    user_type = '0'
            elif request.user.is_instructor():
                    user_type = '1'
            elif request.user.is_student():
                    user_type = '2'
            else:
                    user_type = '3'

            payload = {
                    'user_type': user_type,
                    'username': username,
                    'exp': datetime.utcnow() + timedelta(seconds=JWT_EXP_DELTA_SECONDS)
                }
            jwt_token = jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM)
            return Response({'token': jwt_token.decode('utf-8')})
Run Code Online (Sandbox Code Playgroud)

有效载荷数据返回

{
  "user_type": "0",
  "username": "bus",
  "exp": 1475480008
}
Run Code Online (Sandbox Code Playgroud)

对我来说已经足够了。但是当我请求其他 API url 时,它返回

{
  "detail": "Error decoding signature."
}
Run Code Online (Sandbox Code Playgroud)

小智 1

我可以向您建议的最好的事情就是不要自己实现 JWT 逻辑。请使用该包dj_rest_auth,或者如果您只需要 JWT 逻辑,请使用SimpleJWT. dj_rest_auth 包为您提供了完整的身份验证和授权功能。默认情况下,它还使用 SimpleJWT 作为 JWT 实现和功能的后端。

链接:

https://dj-rest-auth.readthedocs.io/en/latest/

https://django-rest-framework-simplejwt.readthedocs.io/en/latest/