Description:
In the django session docs it says:
You can read it and write to request.session at any point in your view.
But I can't access the session when making a second request to the same view:
views.py
class Login(APIView):def post(self, request):print("before: ", request.session.get("user")request.session["user"] = "admin"print(request.session.get("user")) #outputs 'admin'return Response()
Expected Output:
After the second request (made with jquery $.post) it should output:
"admin"
Output:
Instead it outputs:
None
How can I make sessions available between independend requests?
As mentioned by @AbdulAzizBarkat in the comments, the problem was that the session credentials were not sent to the backend. The way the sessions work in a cross-domain scenario is:
- User is verified in backend
- Session is sent to the frontend and stored in the browser
- The session credentials have to get sent to the backend on every request
You cannot, however, read this session cookies, like mentioned here:
The browser cannot give access to 3rd party cookies like those received from ajax requests for security reasons, however it takes care of those automatically for you!
The provided solution using ajax and setting xhrFields: { withCredentials: true }
did not work for me.
Answer:
Instead of an ajax request, I used fetch requests.
It is important to set credentials: "include"
since otherwise cookies won't be sent cross-origin. A request looks like this:
fetch(`${API}/login`, {credentials: "include",method: "POST",body: data,
}).then(...).catch(...);