To explain my situation, if I logged in from backend, csrf cookie is set in cookie tab, the problem occur in frontend, if i try to login from there, csrf cookie is not in request header (being undefined), some code provided:
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']
setting SAMESITE protocol to anything else haven't made any change
in views.py, we have login view (class based):
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)
in serializer.py, we got the login serializer:
class LoginSerializer(serializers.Serializer):
email = serializers.CharField(required=False)
password = serializers.CharField(required=False,allow_null=True,allow_blank=True)
in react (frontend side), here is how i am making a post request:
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)
}
})
}
}
this is part of the code btw ^.
edit: I have a csrf view too, not sure how to use it:
class GetCSRFToken(views.APIView):
permission_classes = [AllowAny, ]
def get(self, request, format=None):
return Response({ 'success': 'CSRF cookie set' })
any help is welcomed.