CSRF使用邮递员测试django时失败

问题描述 投票:0回答:1

我有一个django(rest_framework)应用程序,我刚刚在其中添加了一些身份验证。第一次创建帐户并使用该帐户登录很顺利,但随后麻烦就开始了。

现在,无论何时我尝试注册/登录/注销,我都会立即收到一条错误消息,提示csrf验证失败或令牌丢失。

因此,我开始了解它的含义,并得出结论,它对于身份验证非常重要。我不清楚我如何才能在不损害安全性的情况下使应用程序身份验证系统正常工作。

有人可以向我解释如何在不损害csrf令牌的情况下与应用程序通信。 (例如邮递员)预先感谢!

我的代码是相当标准的Django身份验证代码

authentication = [ 
    url(r'^status/$', StatusView.as_view()),
    url(r'^register/$', RegisterView.as_view()),
    url(r'^login/$', LoginView.as_view()),
    url(r'^logout/$', LogoutView.as_view()),
]

--- views.py ---------------

class RegisterView(APIView):
def post(self, request: Request):
    acc = authentication.AccountSerializer(data=request.data)
    helper.validate_serializer(acc)
    return Response(acc.data)


class LoginView(APIView):
    def post(self, request: Request):
        username = request.data.get("username", "")
        password = request.data.get("password", "")
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return Response({"message": "Login successful", "account": authentication.AccountSerializer(user.account).data})
        else:
            return APIException(detail={"message": "Login unsuccessful"})


class LogoutView(APIView):
    def post(self, request: Request):
        logout(request)
        return Response({"message": "Logout successful"})


class StatusView(APIView):
    def get(self, request: Request):
        if request.user.is_authenticated:
            return Response({"message": "User is authenticated"})
        else:
            return Response({"message": "User is not authenticated"})
django django-rest-framework django-authentication django-csrf
1个回答
0
投票

[尝试清除邮递员的cookie,然后查看。如果您的问题得到解决,请尝试不使用会话身份验证,而将豁免使用csrf装饰器进行竞争(注意:豁免csrf是有风险的,但对于开发而言,您可以这样做=

© www.soinside.com 2019 - 2024. All rights reserved.