last day (16 days later) » 

01:03
0
A: React & Django - WARNING:django.request:Forbidden: /api/user - SessionAuthentication

VonCYou have: Client (React) --> [HTTP Request with CSRF Token] --> Django Backend /\ | +--- [Session Authentication & CSRF Validation] For SessionAut...

Thank you very much. However, I'm still getting Forbidden: /api/user (after register/login, and then I reload the page). You can find my settings.py and the logs here: gist.github.com/axilaris/f0f41dc843c05d0f4cfd40cfefb3478e. I do undertand generally the flow how front end should ensure withCredentials = True and I think CORS_ALLOW_CREDENTIALS = True. The rest I'm not to sure. I am using port 80 in docker, so I have disabled SECURE for CSRF_COOKIE_SECURE = False and SESSION_COOKIE_SECURE = False. What is the problem why is it still Forbidden ?
Is there a way I can help troubleshoot ? Does the logs I gave you help ?
@Axil I have edited the answer with some debugging suggestions for you to try.
Thanks. It still doesnt work. I have committed your solution and troubleshooting code into github. You can see some of the summary on the changes and the network logs here: gist.github.com/axilaris/8941e1e6254e62e5c96e29e8241d8bba. I have noticed something, the csrftoken from getCookie is 1qJvVnbBRdkPgGBYd8KLK7wDg7KOE2QU but in network logs for login response is rsyLvHLLNAIumReGxLa63PONPM3klYIq. I'ved even tried to clear the browser cache like this imgur.com/a/3Aly1In. I tried both Chrome and MS Edge Browser to verify.
@Axil I have edited the answer to address your comment.
I think in your latest comment, that is exactly what I have done, if you looked into App.js, I'ved tried to update csrftoken from getCookie to axios to api/register, api/login, api/user. github.com/axilaris/docker-django-react-celery-redis/blob/ma‌​in/…. Do you mind if we do a zoom call ? I'ved really searched all over, not sure what is wrong. is there a possibility we can read out the correct Set-Cookie csrftoken ?
01:03
@Axil I have updated the answer to address your last comment.
I did a new trick that WORKS. I created a new axios instance on api/login and on the api/user. The surprise is that api/login generates a new csrftoken just for the first time in the console print. and then, api/user works. I havent applied the code to github yet but you can check the App.js code that uses a new axiosInstance gist.github.com/axilaris/1076e8c25c810b03b701d8b49f4fa7f6. Could you explain why the original axios.create() that is can be reusable everywhere does not work ? I dont like this new method I have developed to create a new connection everytime.
@Axil I have updated the answer to address your comment.
Hi, really appreciate so much you have helped. Coming to this point is already great!
I just would like more understanding, as this hack didnt look so clean. or is it.
maybe its a residue of Docker ?
or maybe port 8000
ok let me read it
let me just try that then, i guess its just plugging in the code only as I think this interceptors will be executed the request (https://axios-http.com/docs/interceptors):

axios.interceptors.request.use(function (config) {
// Retrieve and set the CSRF token here
config.headers['X-CSRFToken'] = Cookies.get('csrftoken');
return config;
});
01:22
It didnt work, This is the App.js code with axios interceptor gist.github.com/axilaris/32111449eccf62d6a0b45c6b06cae573. May its the wrong location. Let me try within the App() function
@Axil When you set up an interceptor, the interceptor is attached to the specific Axios instance (or the global Axios object) on which you call .interceptors. That means that if you define an interceptor on the global Axios object (axios.interceptors), it will not automatically apply to separate Axios instances created via axios.create() unless those instances inherit or explicitly define their own interceptors.
To make sure your CSRF token update logic applies to requests made with the `client` instance, you should attach the interceptor directly to this instance:

```javascript
// Define the client instance
const client = axios.create({
baseURL: "http://127.0.0.1:8000"
});

// Attach the interceptor to the client instance
client.interceptors.request.use(function (config) {
// Retrieve and set the CSRF token here
config.headers['X-CSRFToken'] = Cookies.get('csrftoken');
return config;
});
```

By attaching the interceptor directly to the `client` instance, you make sure every request made with thi
oh
my bad
let me run through again, sorry it takes awhile, this docker-compose script is not optimized, keeps on doing npm install each round. Will optimize later.
@Axil Also, the approach you have found to work, involving creating new Axios instances or attaching interceptors directly to specific instances, is not a "hack" in the negative sense but rather a practical solution to a common challenge in web development: managing stateful headers across changing states in a web application.
Especially in applications using CSRF tokens, where tokens must be refreshed or updated based on user state changes (e.g., login, logout) to maintain security and application functionality.
Axios interceptors are specifically designed to allow you to intercept requests or responses before they are handled by then or catch. Using interceptors to dynamically update headers based on the latest application state (like the current CSRF token) is precisely within their intended use case.
The use of Docker containers for development or deployment does not directly influence the need for or the effectiveness of using Axios instances or interceptors in this way.
your solution didnt work. interceptor does work, its called each time. I suspect it maybe a port issue since its attached to :8000. let me try create new instance each time "explicitly specifying the host and port"
i just want to know the root of this evil :)
i mean there is a solution, just very curious what is it actually
gist.github.com/axilaris/2047ab7bbac89349aaca9a04c8e3b3af <-- manually specifying port 8000 didnt work. I dont know if you have seen the docker-compose, i think nginx is routing it so that its server on port 80
const axiosInstance = axios.create({
baseURL: "http://127.0.0.1:8000",
withCredentials: true
})

const csrfToken = Cookies.get('csrftoken');
console.log("XXX /api/user csrfToken:" + csrfToken);
// Set the CSRF token in the Axios default headers
axiosInstance.defaults.headers.common['X-CSRFToken'] = csrfToken;
axiosInstance.defaults.xsrfCookieName = 'csrftoken';
axiosInstance.defaults.xsrfHeaderName = 'X-CSRFToken';
axiosInstance.defaults.withCredentials = true;

axiosInstance.get("/api/user")
.then(function(res) {
maybe remove the port 8000 is the root cause of this
01:44
In a development environment where services like Django and React run in separate Docker containers or under different ports on the same host, making sure that the frontend makes requests to the correct backend service URL (including the correct port) is important.
You can adjust your Axios instance creation to explicitly set the base URL each time you create a new instance, which includes the correct host and port:

```javascript
function createAxiosInstance() {
// Replace 'backend_host' with your Django backend host (e.g., 'localhost')
And then use this function to create a new Axios instance whenever you need to make a request:

```javascript
const client = createAxiosInstance();

client.post("/api/login", { email, password })
.then(response => {
console.log(response.data);
// Handle successful login
})
.catch(error => {
console.error("Login error:", error);
// Handle error
});
```
I have to go, but I will log back in later on today
thanks a lot. just an update. I just do something primitive by removing the port in the original code. it didnt work. probably i try also your solution to make sure csrf token is updated with the interveptors as well
will update more
if all really not work, will then resort to the old create new instance method.
 
3 hours later…
05:20
UPDATE:
1. Your recommended code with interceptors DIDNT WORK: gist.github.com/axilaris/b6323bfa5f9dcb24123d7048a9e3f2d6
2. In Docker - This code with separate request with axios WORK (without port 8000). I'ved included in logout so every login now has print of new csrftoken. api/user is SUCCESS (so its working) gist.github.com/axilaris/5b532d7b39f5b097a58fc32ef89200e7
3. Without Docker (Django and React started separately), didnt work with no.2 code with small modifications. gist.github.com/axilaris/f71b40887f431f0cc32ca345389cb5b5. I added in settings.py CORS_ALLOWED_ORIGINS with localhost:3000. And all the request in axiosinstance with 127.0.0.1:8000
For no.3, It CAN access login but CANNOT /api/user (because of permission_classes = (permissions.IsAuthenticated,)

2024-03-10 05:06:45,624 WARNING Forbidden: /api/user
[10/Mar/2024 05:06:45] "GET /api/user HTTP/1.1" 403 58
[10/Mar/2024 05:07:06] "OPTIONS /api/login HTTP/1.1" 200 0
2024-03-10 05:07:06,936 DEBUG XXX UserLogin post
[10/Mar/2024 05:07:07] "POST /api/login HTTP/1.1" 200 52
Forbidden: /api/user
2024-03-10 05:07:13,887 WARNING Forbidden: /api/user
[10/Mar/2024 05:07:13] "GET /api/user HTTP/1.1" 403 58
 
9 hours later…
14:04
github.com/axilaris/docker-django-react-celery-redis/tree/… <-- this is the branch for no.3 where django is running on port 8000 and react is running on port 3000. For this, login with separate axios request doesnt seem to obtain a new csrftoken.
 
6 hours later…
19:36
@Axil Do you have CORS_ALLOW_CREDENTIALS set to True in your Django settings?
Is your Django project correctly configured to use session authentication. That would mean including `'rest_framework.authentication.SessionAuthentication'` in the `DEFAULT_AUTHENTICATION_CLASSES` of your Django REST Framework settings.

```python
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
],
}
```
After a successful login, verify on the Django side (perhaps with debug prints or logging in your login view) that the session is indeed being created and is active. Additionally, inspect the response headers for the login request to make sure the Set-Cookie header contains the session id.
If your login process involves refreshing or changing the CSRF token, make sure the frontend fetches the updated CSRF token after login. Since you are using cookies to manage the CSRF token, this step might involve re-fetching the CSRF token from the cookie (using Cookies.get('csrftoken')) after the login request completes.

  last day (16 days later) »