[英]403 Forbidden CSRF Verification Failed React Django
Good day,再会,
i have been trying to set the csrftoken, so my login would be safe.我一直在尝试设置 csrftoken,这样我的登录就安全了。 I have followed the instructions of this stackoverflow question, but had no luck.我已经按照这个stackoverflow 问题的说明进行操作,但没有运气。 I have done some experimenting by setting SESSION_COOKIE_SECURE
to False
and setting CSRF_COOKIE_SECURE
to False
.我通过将SESSION_COOKIE_SECURE
设置为False
并将CSRF_COOKIE_SECURE
设置为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.我也尝试过将标头中的X-CSRFToken
命名为csrftoken
和X-CSRFTOKEN
的不同类型,但它们都不起作用。 Any suggestions?有什么建议么?
Edit: I also test it on incognito mode.编辑:我也在隐身模式下测试它。 Perhaps that might be the problem?也许这可能是问题所在?
views.py视图.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设置.py
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE=True
login.js登录.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 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在 index.html (templates>frontend>index.html) 里面把这一行放在下面
<script type="text/javascript">window.CSRF_TOKEN="{{ csrf_token }}"</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.