简体   繁体   中英

403 Forbidden CSRF Verification Failed React Django

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;

Alright got it!

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

<script type="text/javascript">window.CSRF_TOKEN="{{ csrf_token }}"</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM