Mervyn Lee
Mervyn Lee

Reputation: 2197

Django Authentication through API

I want to provide some API such as login and logout through ReactJS interface. I see the Django document here that accounts/ provides some urls such as login and logout. Is that possible that I just leverage the login and logout api under accounts/ without creating template and try them out in Postman? I tried with POST request:

{
    "username": "admin",
    "password": "admin"
}

and cookie with csrfmiddlewaretoken and csrftoken but got the error Forbidden (CSRF token missing or incorrect.): /accounts/login/

Upvotes: 1

Views: 154

Answers (1)

Resley Rodrigues
Resley Rodrigues

Reputation: 2288

As for using the in-built Django forms for authentication, it cannot be done by passing JSON data. Instead, it is much better to create your own API endpoint and return some sort of authentication token to the client to use for future requests. In such cases, you might not need the CSRF token.

Alternatively, you could host your react app within a Django page, and use Django for authentication, in which case you don't need to handle the token as Django will do it for you. But this is not a very common approach and might not work in all cases.


As for injecting the CSRF token, there are a few different ways to do so when you are using ReactJS

Handling CSRF Tokens in React/Axios

For Axios client you have three options:

  1. you can manually attach the CSRF token in the header of each Axios call
  2. you can use the Axios xsrfHeaderName for each call
  3. you can use a default xsrfHeaderName (axios.defaults.xsrfHeaderName = "X-CSRFToken")

Here is how you can simply use the CSRF token with Axios without any further configuration:

import axios from 'axios';

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

Handling CSRF Tokens in React/Fetch

fetch(url, {
    credentials: 'include',
    method: 'POST',
    mode: 'same-origin',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-CSRFToken': csrftoken
    },
    body: {}
   })
  }

Handling CSRF Using React/Redux

If you are using Redux to manage your application state you can use redux-csrf to handle CSRF token in Redux.

You can use by first installing it from npm with

npm install redux-csrf --save

Then you can use the setCsrfToken(token) API that set the CSRF token in the Redux store.

Upvotes: 1

Related Questions