I’m having trouble with cookie-based authentication in my Django
+ React
app. I’ve set the cookie on the backend, but it’s not being sent with subsequent requests from the frontend React
(Using Vite
) app running on Google Chrome
.
I’m trying to implement authentication using cookies in a Django
backend using Simple JWT
. After a successful login, I set an authentication cookie (“CAT”) in Django
. Here’s the code I use to set the cookie:
final_response.set_cookie(
"CAT",
combined_token,
httponly=True,
secure=False,
samesite="None",
max_age=86400,
path="/",
)
return final_response
Setting.py at the Django server:
CORS_ALLOW_ALL_ORIGINS = False
CORS_ALLOWED_ORIGINS = ["http://localhost:5173/"]
CORS_ALLOW_CREDENTIALS = True
SECURE_CROSS_ORIGIN_OPENER_POLICY = "same-origin"
I can see the cookie stored in Chrome after logging in:
However, when my React
app makes subsequent requests, the browser doesn’t seem to include the cookie, and I get an authentication failure (“Cookie not found”). Here’s my Axios
request setup in the React
app:
try {
const auth_response = await axios.get(
"http://my-django-server/api/auth/auth-checker",
{
headers: {
"Content-Type": "application/json",
},
withCredentials: true,
timeout: 5000,
}
);
console.log(auth_response?.data);
if (auth_response?.status === 200) {
navigate("/profile");
} else {
console.error("Unauthorized access. Please try again.");
}
} catch (error) {
console.error("An error occurred. Please try again.", error);
}
Manual authentication works:
Interestingly, when I manually set the cookie in an Axios
request from the terminal, the request works as expected and I get an authenticated response. However, in the browser, it fails.
getRegularHeader(port: string): Record<string, string> {
return {
"Content-Type": "application/json",
Origin: `http://localhost:${port}`,
};
}
const token = readlineSync.question("Enter CAT token: ");
try {
const response = await axios.get(url, {
headers: { ...this.getRegularHeader(port), Cookie: `CAT=${token}` },
withCredentials: true,
timeout: 5000,
});
return response;
} catch (error) {
console.error(`Failed to authenticate: ${error}`);
return null;
}
There is also a message from Google Chrome
:
What I’ve Tried:
- Checked in both Chrome and Edge with the same result.
- Verified that withCredentials: true is set in the Axios request.
- Attempted different cookie settings (e.g., SameSite=None, Secure=False).
Questions:
- Why are the browsers not sending the cookie with my requests?
- Are there any specific settings or configurations I might be missing in either Django or React?