1

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/

2
  • 1) Your link is broken 2) You need to include a CSRF token in all POST requests. For JSON APIs you can include it in the headers as "X-CSRF-Token" or change your settings to not use CSRF (bad practice) Commented Jan 31, 2019 at 8:02
  • link corrected. Sorry Commented Jan 31, 2019 at 8:09

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.