Django部署Render平台时无法读取CSRF Token的问题排查与解决咨询
Django部署Render平台时无法读取CSRF Token的问题排查与解决咨询
我正在开发一个Django后端,部署在Render平台上。现在我需要测试邮箱验证的OTP发送逻辑,但POST请求需要带上csrftoken才能正常工作。
一开始Firefox里Cookie没有被设置(但Chrome里可以),因为Firefox要求Cookie必须设置partitioned属性,而Django目前还不支持这个,所以我加了自定义中间件来处理。但现在又遇到了新问题:我无法读取到csrftoken。
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
前端JS代码(live.html中)
请求来源页面:http://127.0.0.1:8001/live.html
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 token not found. Please refresh the page.
控制台输出:
live.html:169 live.html:199 null live.html:202 CSRF token not found in headers!
但Cookie确实已经被设置:
HttpOnly未勾选,Secure已勾选,SameSite为None,Partition Key Site设置为"http://127.0.0.1",Cross Site已勾选。
Firefox浏览器表现
页面提示:CSRF token not found. Please refresh the page.
控制台输出:
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没有被设置。
我尝试把HTML页面部署到GitHub Pages提供HTTPS环境,但结果和上面完全一样。
我的疑问
- 为什么明明在DevTools里能看到CSRF Token,
document.cookie却返回空或者null? - 我该如何正确提取CSRF Token并在请求中发送,让Django接受?
- 是否有额外的安全设置阻止了JavaScript访问Cookie?
非常感谢任何相关的见解和建议!
备注:内容来源于stack exchange,提问作者Piyush Chaudhary
相关产品推荐
相关产品推荐

