Using the Django authentication system within a React SPA

Viewed 1570

I'm currently developing an application based on React and Django.

I'm using Django rest Framework to create REST APIs that are consumed in the React frontend. This works pretty well.

I'm now willing to implement authentication using the Django session authentication system for the application. I could create authentication APIs. However, I would prefer using Django authentication system.

How can I use Django authentication views and forms in a React SPA?

A code snippet describing the overall architecture would be much appreciated. I can't figure out how to have the React app "calling Django code" (apart from DRF APIs)!

My question is about authentication, but I could reuse the same mechanism for other Django views.

1 Answers

In summary

Once your users are logged in, all of their requests will be associated with their Django user, accessible in request.user. As such you don't need to interact with Django's authentication views through React after login.

In detail

Assuming you have:

  1. 'django.contrib.auth' and 'django.contrib.contenttypes' in your INSTALLED_APPS
  2. SessionMiddleware and AuthenticationMiddleware in your MIDDLEWARE setting
  3. The auth urls in your main urls.py file:
path('accounts/', include('django.contrib.auth.urls')

Then your users can login using the view at /accounts/login/. After that they will get a session cookie which is sent with every request made to your Django server. This cookie is used by Django to identify which user made the request. Django gives that information to you in request.user.

You can use this object to check permission in your DRF views:

if request.user.is_staff:
    # Do something for staff users.
else:
    # ...

Notes

  1. Once users are authenticated, you'll want to check that an individual user has permission to access the data they request - but permission is a different topic. The DRF has documentation about permissions.

  2. For non-GET requests, you should include a CSRF token with your request. You can use either the Django {% csrf_token %} tag to get the token, or get it from the cookies: var csrftoken = Cookies.get('csrftoken');

Related