首页 > 解决方案 > http响应未在浏览器中设置cookie

问题描述

TLDR:

以下response标头未在浏览器中设置 cookie:

Access-Control-Allow-Origin: *
Allow: GET, HEAD, OPTIONS
Content-Length: 7
Content-Type: application/json
Date: Tue, 27 Apr 2021 15:58:02 GMT
Referrer-Policy: same-origin
Server: WSGIServer/0.2 CPython/3.9.4
Set-Cookie: csrftoken=r5r2YcZZvJKs79cbLd24VSyNscpUsxJB6UuWiWO2TXriy6B4r8KDZrwSDyI091K1; expires=Tue, 26 Apr 2022 15:58:02 GMT; Max-Age=31449600; Path=/; SameSite=Lax
Vary: Accept, Cookie, Origin
X-Content-Type-Options: nosniff
X-Frame-Options: DENY

我的request标题:

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en-US;q=0.9,en;q=0.8
Cache-Control: no-cache
Connection: keep-alive
Host: 127.0.0.1:8000
Origin: http://localhost:3000
Pragma: no-cache
Referer: http://localhost:3000/
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"
sec-ch-ua-mobile: ?0
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.85 Safari/537.36

我是 Django 新手,反应和“http 标头”相关的东西。

我的 django 开发服务器运行在:

http://127.0.0.1:8000/

我的反应开发服务器运行在:

http://127.0.0.1:3000
  1. 为了访问该网站,需要登录。因此,通过配置 react-router并遵循此模板,所有未经授权的请求都会首先重定向到登录页面。所以,到目前为止,没有进行任何 api 调用。
  2. 为了发布登录数据,我需要由服务器设置 csrf 令牌。但由于我没有进行任何 api 调用,我/api/csrf/明确创建了一个端点来设置 csrf 令牌。
# URL: /api/csrf/
class CSRFGet(APIView):
    """
    Explicitly set csrf cookie
    """

    @method_decorator(ensure_csrf_cookie)
    def get(self, request):
        return Response('hello')

useProvideAuth当挂接钩子时,我称之为端点。

function useProvideAuth() {
    const [token, setToken] = useState(null);

    const login = (username, password) => {
        return axios.post(
            '/auth/',
            {
                username: username,
                password: password
            })
            .then(response => {
                setToken(response.token) 
            })
    }

    useEffect(()=> {
        axios.get(
            '/csrf/'
        )
    },[])

    return {
        token,
        login,
    }
}
  1. 为了检索和设置这个 cookie,我遵循了官方 Django 文档我还使用django-CORS-headers allow all origins启用了 CORS 策略。

现在,当我向任何页面发出请求时,它会重定向到登录页面,我可以看到api/csrf/响应:

Set-Cookie: csrftoken=LgHo2Y7R1BshM4iPisi5qCXhdHyAQK7hD0LxYwESZGcUh3dXwDu03lORdDq02pzG; expires=Tue, 26 Apr 2022 06:29:23 GMT; Max-Age=31449600; Path=/; SameSite=Lax

但是,cookie 根本没有设置。为什么会这样?

我获取 csrf cookie 的方法是否正确?如果我用这种方法制造任何安全漏洞,请告诉我。

标签: reactjsdjangocookiesdjango-rest-frameworkhttp-headers

解决方案



推荐阅读