为了解释我的情况,如果我从后端登录,csrf cookie会设置在cookie选项卡中,在前端出现问题,如果我尝试从那里登录,请求头中没有csrf cookie(未定义),以下是提供的一些代码:
settings.py:
ALLOWED_HOSTS = ['*']
ACCESS_CONTROL_ALLOW_ORIGIN = '*'
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
ACCESS_CONTROL_ALLOW_CREDENTIALS = True
ACCESS_CONTROL_ALLOW_METHODS = '*'
ACCESS_CONTROL_ALLOW_HEADERS = '*'
'''
SESSION_COOKIE_SECURE = True
'''
CSRF_COOKIE_SAMESITE = 'None'
SESSION_COOKIE_SAMESITE = 'None'
CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:3000",'http://127.0.0.1:8000','http://localhost:3000']
将 SAMESITE 协议设置成其他值并没有产生任何变化。
在 views.py 中,我们有登录视图(基于类):
class LoginView(views.APIView):
permission_classes = [AllowAny,]
serializer_class = serializer.LoginSerializer
def post(self,request):
data = serializer.LoginSerializer(data=request.data)
print(data.is_valid())
if data.is_valid():
email = data.data['email']
password = data.data['password']
auth = authenticate(username=email,password=password)
if auth:
login(request,auth)
return HttpResponse("Success",status=200)
else:
print(password == "")
if email == "" and password =="":
return HttpResponse('Both email and password field are empty',status=400)
elif email == "":
return HttpResponse('Email field is empty',status=400)
elif password == "":
return HttpResponse('Passowrd field is empty',status = 400)
else:
return HttpResponse("Both email and password fields are empty",status=400)
在serializer.py中,我们有登录序列化程序:
class LoginSerializer(serializers.Serializer):
email = serializers.CharField(required=False)
password = serializers.CharField(required=False,allow_null=True,allow_blank=True)
在React(前端)中,这是我进行POST请求的方式:
function Login(){
const [login,setLogin] = useState({'email':'','password':''})
const {email,password} = login
const navigate = useNavigate()
let handleChange = (e)=>{
setLogin(
{
...login,
[e.target.name]:e.target.value
}
)
}
let handleSubmit = (e)=>{
e.preventDefault()
axios.post('http://127.0.0.1:8000/login/',login,{headers: {'Content-Type': 'application/json','X-CSRFToken':Cookies.get('csrftoken')}}).then(
(res)=>{
console.log(res)
console.log(Cookies.get('csrftoken')) //undefined here
}
).catch((e)=>{
console.log(e)
}
})
}
}
这是代码的一部分,顺便提一下^。
编辑: 我还有一个CSRF视图,不确定如何使用:
class GetCSRFToken(views.APIView):
permission_classes = [AllowAny, ]
def get(self, request, format=None):
return Response({ 'success': 'CSRF cookie set' })
欢迎任何帮助。