inertiajs / inertia-django

The Django adapter for Inertia.js
MIT License
326 stars 32 forks source link

CSRF token not being sent automatically #14

Closed MichaelNZ85 closed 1 year ago

MichaelNZ85 commented 1 year ago

I'm at my wits' end trying to get Django to send the CSRF token to the backend (project here).

The CSRF token is being sent in the cookie, but I cannot set an X-XSRF-Token header as a global header on Axios.

Would it be possible to include this by default in inertia-django, like the Laravel implementation already does?

BrandonShar commented 1 year ago

Hey @MichaelNZ85, I took a look at your last commit and you're nearly there!

In your main.js add the following lines:

axios.defaults.xsrfHeaderName = "X-CSRFToken"
axios.defaults.xsrfCookieName = "csrftoken"

and then on your login view or any unauthenticated forms, add the following decorator:

from django.views.decorators.csrf import ensure_csrf_cookie

@ensure_csrf_cookie
@inertia('YourComponent')
def your_view(request):
  pass

Would it be possible to include this by default in inertia-django, like the Laravel implementation already does?

We're discussing this internally now, but I haven't come up with anything I really like yet. There's an important distinction here that the Laravel Inertia adapter does not automatically handle CSRF, the Laravel framework itself does, so it's a non-issue for that adapter. I think it makes sense to automatically handle CSRF somehow since it's in such contrast to how Django wants it to work, but I want to make sure we do that in a way that doesn't conflict with the Django framework itself.

MichaelNZ85 commented 1 year ago

I tried that and still no luck. I've created an issue on the template I was using, but the creator hasn't replied as of yet.

I think it would be great if the actual Inertia framework handled the CSRF token.

BrandonShar commented 1 year ago

Using @ensure_csrf_cookie didn't work? It's possible there's a different issue here.

I think it would be great if the actual Inertia framework handled the CSRF token.

Yes, I agree; I've come around on this after talking to a few people. I'll get this added!