Не удается прочитать "csrftoken" из файлов cookie (Django)
Я работаю над серверной частью Django. Серверная часть развернута на Render, и я тестирую логику проверки электронной почты, отправляя OTP, но для этого мне нужно отправить "csrftoken" для запроса POST.
Сначала файл cookie не устанавливался в файлах cookie в firefox (но устанавливался в chrome), поскольку он запрашивал, чтобы для файла cookie был установлен атрибут секционирования, поскольку django еще не поддерживает его, мне пришлось включить пользовательское промежуточное программное обеспечение, чтобы сделать это.
В настоящее время по какой-то причине я не могу прочитать токен csrf.
views.py:
@ensure_csrf_cookie
def register(request):
if request.method == "POST":
......
elif request.method == "GET":
return JsonResponse({"message": "GET request handled"}, status=200)
prod.py:
from .common import *
CSRF_TRUSTED_ORIGINS = [
"http://127.0.0.1:8001",
"http://localhost:8001",
"https://forkmemaybe.github.io/temp/",
]
CSRF_COOKIE_SAMESITE = "None"
CSRF_COOKIE_SECURE = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = [
"http://127.0.0.1:8001",
"http://localhost:8001",
"https://forkmemaybe.github.io/temp/",
]
SESSION_COOKIE_SAMESITE = "None"
SESSION_COOKIE_SECURE = True
HTML-страница, на которую я отправляю запросы с URL: [http://127.0.0.1:8001/live.html]
......
<script>
function getCookie(name) {
let cookieValue = null;
console.log(document.cookie);
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;
}
fetch("https://App-Name.onrender.com/register/", { // Initial GET request
method: "GET",
credentials: "include",
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// const csrftoken = response.headers.get("X-CSRFToken");
const csrftoken = getCookie("csrftoken");
console.log(csrftoken);
if (!csrftoken) {
console.error("CSRF token not found in headers!");
document.getElementById("errorMessage").textContent = "CSRF token not found. Please refresh the page.";
return;
}
console.log("CSRF Token from header:", csrftoken);
........
браузер chrome
На странице браузера отображается сообщение о том, что токен CSRF не найден. Пожалуйста, обновите страницу.
live.html:169
live.html:199 null
live.html:202 CSRF token not found in headers!
в chrome устанавливается файл cookie.
it has HttpOnly unchecked, Secure checked, SameSite None, Partition Key Site set to "http://127.0.0.1", Cross Site is checked.
браузер firefox
На странице браузера я получаю сообщение "Токен CSRF не найден. Пожалуйста, обновите страницу."
This page is in Quirks Mode. Page layout may be impacted. For Standards Mode use “<!DOCTYPE html>”.
live.html
A meta tag attempting to declare the character encoding declaration was found too late, and the encoding was guessed from content instead. The meta tag needs to be moved to the start of the head part of the document. live.html:147:1
<empty string> live.html:169:21
null live.html:199:21
CSRF token not found in headers! live.html:202:25
<anonymous> http://127.0.0.1:8001/live.html:202
файл cookie не устанавливается.
Я попытался создать среду HTTPS, разместив свою HTML-страницу на github pages, но результат был таким же, как и выше.
Вопрос:
- Почему файл document.cookie возвращает значение null, когда токен CSRF четко виден в DevTools?
- Как я могу правильно извлечь токен CSRF и отправить его в запросе, чтобы Django принял его?
- Есть ли какие-либо дополнительные настройки безопасности, которые предотвращают доступ JavaScript к файлам cookie?
Был бы признателен за любую информацию.
Почему файл document.cookie возвращает значение null, когда токен CSRF четко виден в DevTools
Это потому, что, предположительно, это только httponly. Это ключевая часть безопасности токенов CSRF!