skip to Main Content

I am trying to send the csrf token i genenrated

here is the csrftoken generation

  const [cr , setCR] = useState('')

    const getcsrf = async () => {
        await fetch('http://localhost:8000/auth/gettoken')   
        .then( async res => await res.json()).then(data =>{
            setCR( data.crsftoken)
            console.log(cr)
           })
     }

     useEffect( () => {
        getcsrf()
     },[] )

after i have obtained the token i try to send it using fetch

const handlelogin = async () => {

                 if(cr !== ''){
                    console.log(cr)
        await fetch('http://localhost:8000/auth/login',
        {method : "POST",
        credentials: "include" ,
         headers: {
            "Content-Type": "application/json",
            "X-CSRFToken" : cr
         },
         body : {
            "username" : username, 
            "password" : password
         }
         
        }
        ).catch(err => console.log(err))}else{console.log('cr is null')}
    }

the csrf token is generated i can see it when i console.logged it but the fetch brings back a 403 forbidden error

     Forbidden (CSRF token from the 'X-Csrftoken' HTTP header incorrect.): /auth/login
     [09/Nov/2023 05:49:59] "POST /auth/login HTTP/1.1" 403 2553

i am expecting it to post to the url i gave it. what is wrong with it?

2

Answers


  1. CSRF Middleware token is generated automatically with each request so the value you sent has a probability of not matching subsequent requests as there is a GET request in the middle.

    If you want to do CSRF, it is better to manage it manually not through CSRF Middleware and maybe Django Rest framework has a fix for this.

    CSRF is easy.

    1. You send a value to the client and save the same value to the session.
    2. When you receive the request you check the received value against the saved value. If they match, process the request otherwise return an error.
    Login or Signup to reply.
  2. In your Django template, include {% csrf_token %} within the form.
    Retrieve the CSRF token in your React component: for example const csrfToken = document.getElementsByName("csrfmiddlewaretoken")[0].value;

    fetch('your_api_endpoint', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': csrfToken, //Include the CSRF token in your fetch request headers:
        },
        // Add other options and body as needed
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
    

    Configure Django to accept the CSRF token from the header: for example In settings.py files you have token (CSRF_HEADER_NAME = ‘HTTP_X_CSRFTOKEN’).
    Note -> Ensure your Django view allows POST requests from your React frontend.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search