Ok I understand and it’s really too much code to post here. All I know it works and there isn’t any field called csrfmiddlewaretoken
so don’t know why it works then because I read the field must be there but it’s not and I make post, put and delete requests without issues.
As far as this goes if the request comes from a domain (localhost) and localhost is in that list of CSRF_TRUSTED_ORIGINS = [
then why is the access still be denied because of CSRF?
I log in on the Django side of things using a form and a normal view:
def loginpage(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
if '@' in username:
user = authenticate(request, email=username, password=password)
else:
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
messages.success(request, 'Login successful')
return redirect('homepage')
else:
messages.error(request, 'Invalid credentials. Please try again.')
logged_in = request.user.is_authenticated
if logged_in:
return redirect('homepage')
else:
return render(request, 'pages/login.html', {'form': LoginForm, 'resetform': CustomPasswordResetForm})
it works perfectly and it then creates two cookie and they are:
csrftoken:"k3rDF6l6jSIA9DoTwoZDyDNNs2uvBax2"
sessionid:"gnb8osj0ww615coqvh3b9ppllw218urq"
When I make a POST, PUT, DELETE request to the back end then I get a 403 error and here are the request headers:
POST
http://localhost:8000/api/v1/users/logout/
Status
403
Forbidden
VersionHTTP/1.1
Transferred502 B (45 B size)
Referrer Policystrict-origin-when-cross-origin
Request PriorityHighest
DNS ResolutionSystem
access-control-allow-credentials
true
access-control-allow-origin
http://localhost:8080
Allow
POST, OPTIONS
Content-Language
en
Content-Length
45
Content-Type
application/json
Cross-Origin-Opener-Policy
same-origin
Date
Tue, 09 Jan 2024 15:55:57 GMT
Referrer-Policy
same-origin
Server
WSGIServer/0.2 CPython/3.10.12
Vary
origin, Accept-Language, Cookie
X-Content-Type-Options
nosniff
X-Frame-Options
DENY
Accept
application/json, text/plain, */*
Accept-Encoding
gzip, deflate, br
Accept-Language
en-US,en;q=0.5
Cache-Control
no-cache
Connection
keep-alive
Content-Length
0
Cookie
csrftoken=k3rDF6l6jSIA9DoTwoZDyDNNs2uvBax2; sessionid=gnb8osj0ww615coqvh3b9ppllw218urq
Host
localhost:8000
Origin
http://localhost:8080
Pragma
no-cache
Referer
http://localhost:8080/
Sec-Fetch-Dest
empty
Sec-Fetch-Mode
cors
Sec-Fetch-Site
same-site
User-Agent
Mozilla/5.0 (X11; Linux x86_64; rv:121.0) Gecko/20100101 Firefox/121.0
As you can see the token and session id is in the headers and I can make get requests fine but any request where the cookie must be sent (which I presume is being sent because it’s in the header) gives me 403 error.
Why is the session id cookie being sent and accepted but the csrf cookie is not?
How do I possibly fix this?