【问题标题】:How to delete the Token from backend in Django如何在 Django 中从后端删除令牌
【发布时间】:2021-02-25 13:52:17
【问题描述】:

我正在使用 django rest-auth 和 django rest api。我可以通过在可浏览的 api 中调用 rest-auth/logout 来注销用户,它将从数据库中删除令牌。在可浏览的 api 中,我不必将令牌与注销 url 一起发送。我从 React js 前端调用了相同的 url rest-auth/logout,它给出的响应为“成功注销”,但 Token 仍保留在数据库中。如何通过从前端调用 url 来删除 Token。

【问题讨论】:

    标签: python reactjs django django-rest-auth


    【解决方案1】:

    您必须发送DELETE 请求并使用此代码:

    class LogoutView(APIView):
    """ Logout User """
    
    @staticmethod
    def delete(request, *args, **kwargs):
        request.user.auth_token.delete()
        data = {
            "message": "You have successfully logged out.",
        }
        return Response(data, status=status.HTTP_200_OK)
    

    【讨论】:

    • 我试过这段代码。它从数据库中删除令牌。但是用户停留在可浏览的 api 中,即使在删除令牌后我也可以调用身份验证所需的视图
    • 来自 django 的用户默认注销请求以处理用户会话
    • @NavanjaneVidunuwanKindelpiti 你是怎么解决的?
    【解决方案2】:

    您好,我会使用不同的方法。

    1. 每次登录、删除和创建一个新令牌
    2. 每次注销调用logout方法
    from django.contrib import auth
    
    class LoginView(APIView):
    """ Login User """
    
        @staticmethod
        def post(request, *args, **kwargs):
            # get username and password
            user = auth.authenticate(username=username, password=password)
            if user is not None:
                Token.objects.filter(user=user).delete()
                token = Token.objects.create(user=user)
                auth.login(request, user)
                # redirect to whatever with token key
            # error return here
     
    class LogoutView(APIView):
    """ Logout User """
    
        @staticmethod
        def delete(request, *args, **kwargs):
            auth.logout(request)
            data = {
                "message": "You have successfully logged out.",
            }
            return Response(data, status=status.HTTP_200_OK)
    
    

    【讨论】:

      猜你喜欢
      • 2017-03-29
      • 1970-01-01
      • 2020-03-10
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2021-06-19
      • 1970-01-01
      • 2021-09-20
      相关资源
      最近更新 更多