2

Good day,

i have been trying to set the csrftoken, so my login would be safe. I have followed the instructions of this stackoverflow question, but had no luck. I have done some experimenting by setting SESSION_COOKIE_SECURE to False and setting CSRF_COOKIE_SECURE to False. I've tried also tried different types of naming the X-CSRFToken in the headers to csrftoken and X-CSRFTOKEN but none of them worked. Any suggestions?

Edit: I also test it on incognito mode. Perhaps that might be the problem?

views.py

@ensure_csrf_cookie
def login_view(request):
    if request.method == "POST":
         data = json.loads(request.body)
         # Attempt to sign user in
         username = data.get("username")
         password = data.get("password")

settings.py

SESSION_COOKIE_SECURE = True

CSRF_COOKIE_SECURE=True

login.js

 function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    const csrftoken = getCookie('csrftoken');


 fetch('/api/login', {
            credentials:'include', 
            method: 'POST',
            headers: {
                'X-CSRFToken': csrftoken,
            },
            body: JSON.stringify({
                username: username,
                password: password
               
            })
        })

 <form onSubmit={handleSubmit}>
        <CSRFToken/>
 </form>

csrftoken.js

import React from 'react';


function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        let cookies = document.cookie.split(';');
        for(let i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].toString().replace(/^([\s]*)|([\s]*)$/g, "");
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}


var csrftoken = getCookie('csrftoken');

const CSRFToken = () => {
    return (
        <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} />
    );
};
export default CSRFToken;
Reactord
  • 96
  • 1
  • 11

1 Answers1

0

Alright got it!

inside index.html (templates>frontend>index.html) put this line below

<script type="text/javascript">window.CSRF_TOKEN="{{ csrf_token }}"</script>
Reactord
  • 96
  • 1
  • 11
  • 1
    your question helped me to solve my problem, I did not have to add this line though and I used `js-cookie` to get the csrf token. I hope it helps someone. – 00noob Mar 07 '23 at 02:58