1

我创建了一个自定义登录视图来覆盖 gain_jwt_token 视图,如下所示。

class LoginView(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        user = User.objects.using(self.request.session.get('shop')).get(mobile=str(request.data['mobile']))
        if not user.check_password(request.data['password']):
            return Response({'Error': "Invalid mobile or password"}, status="400")
        exp = datetime.datetime.now() + datetime.timedelta(seconds=settings.TOKEN_EXP_TIME)
        exp = int(datetime.datetime.timestamp(exp))
        orig_iat = int(datetime.datetime.timestamp(datetime.datetime.now()))
        if user:
            payload = {
                'user_id': user.id,
                "username": user.mobile,
                "exp": exp,
                "email": "",
                'mobile': user.mobile,
                "orig_iat": orig_iat
            }
           jwt_token = {'token': jwt.encode(payload, settings.SECRET_KEY)}
           return Response(jwt_token, status=status.HTTP_200_OK)
        else:
            return Response({'Error': "Invalid credentials"}, status=status.HTTP_400_BAD_REQUEST)

        response = super().post(request, *args, **kwargs)
        return response

登录令牌将成功创建后,但是当我想调用 API(来自邮递员)时{"detail": "Invalid signature."}出现错误。

我正在使用 get 方法使用我的 API,并且我已JWT MY_TOKENAuthorization标题中添加。任何想法?

4

1 回答 1

0

我认为您应该使用 jwt_encode_handler 对您的有效负载进行编码。请参见下面的示例。

from rest_framework_jwt.settings import api_settings


jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class LoginView(ObtainJSONWebToken):
     def post(self, request, *args, **kwargs):
        ...
        jwt_token = {'token': jwt_encode_handler(payload)}
        ...
于 2019-09-08T06:33:49.450 回答