这是登录和注销视图的代码。当第一次尝试登录时,cookie 已设置,但注销时,它不会更新 cookie 或从浏览器中删除它,导致登录尝试出错。
@csrf_exempt
def post(self, request):
try:
email = request.data.get('email')
password = request.data.get('password')
user = authenticate(request, username=email, password=password)
if user is not None:
request.session.set_expiry(86400*30) # 30 days
login(request, user)
user_obj = Customer.objects.get(email=email, password=password)
return Response({'user_id': user_obj.id}, status=status.HTTP_200_OK)
else:
return Response({'message': 'Invalid credentials'}, status=status.HTTP_401_UNAUTHORIZED)
except Exception as e:
return Response("Internal Server Error",status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class LogoutView(APIView):
@csrf_exempt
def post(self, request):
try:
logout(request)
# delete cookie
response = JsonResponse({'message': 'Logout successful'}, status=status.HTTP_200_OK)
response.delete_cookie('sessionid')
response.delete_cookie('csrftoken')
return response
except Exception as e:
print('error logout ==>',e)
return Response("Internal Server Error",status=status.HTTP_500_INTERNAL_SERVER_ERROR)```
有同样的问题,可能不是您正在寻找的解决方案,但使用空字符串再次设置 cookie 为我完成了这项工作。
class LogoutAPI(APIView):
permission_classes = [
IsAuthenticated,
]
def post(self, request):
invalidate_user_cache(request.user)
response = Response(
{"msg": "Logged out successfully", "isAuthenticated": False, "user": None},
status=status.HTTP_200_OK,
)
response.set_cookie(
key="access_token",
value="",
expires=1,
httponly=True,
samesite="Strict",
secure=True,
path="/")
response.set_cookie(
key="refresh_token",
value="",
expires=1,
httponly=True,
samesite="Strict",
secure=True,
path="/"
)
return response