Django Ninja Session Auth with React(backend and front-end are in different domains)

My issue is Django Backend and React UI are in different domains and session auth is not working.

I am using Django ninja for backend and React for front-end.
I am using session auth and login endpoint returns both session id and csrf token for client to use.

But if I call other endpoint(/api/health), I get 401 error.
So I digged into the issue and here’s how I can replace the issue.
I run both backend and front-end locally.

In React, If I set env var for backend api url to http://localhost:8000, it works and I can see further requests contain session id and csrf token.

REACT_APP_API_URL=http://localhost:8000

But if I set backend url to http://127.0.0.1:8000, login works fine but /api/health it throws 401(Unauthorized) error.

REACT_APP_API_URL=http://127.0.0.1:8000

And this is my django’s settings.py

ALLOWED_HOSTS = ['*']

CORS_ORIGIN_WHITELIST = ('http://localhost', 'http://localhost:3000', 'http://localhost:3001', 'http://127.0.0.1:3000')

CORS_ALLOW_ALL_ORIGINS = True
CORS_ALLOW_CREDENTIALS = True
SESSION_COOKIE_SAMESITE = "Lax"

Any thoughts?

1 Like