【问题标题】:Laravel Cookie not set despite Set-cookie header being present尽管存在 Set-cookie 标头,但未设置 Laravel Cookie
【发布时间】:2017-07-01 09:53:08
【问题描述】:

我们正在开发一个带有 REST Api 的网站(AngularJS 1.6.1 中的前端,Laravel 5.3 中的后端)。 为了添加 CSRF 保护,我们的后端需要在客户端上设置一个带有随机字符串的后端 cookie。在 laravel 中,我们返回这个响应: response("OK", 200)->cookie("csrf_token", "random_string");

cookie 显然是通过响应设置的:

*Request headers*
POST /v1/auth/admin HTTP/1.1
Host: backend.test
Connection: keep-alive
Content-Length: 295
Accept: */*
Origin: http://frontend.test
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://frontend.test/login
Accept-Encoding: gzip, deflate
Accept-Language: it-IT,it;q=0.8,en-US;q=0.6,en;q=0.4

*Response header*
HTTP/1.1 200 OK
Server: nginx/1.11.3
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive
Access-Control-Allow-Origin: http://frontend.test
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, PATCH
Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Requested-With
Access-Control-Allow-Credentials: true
Cache-Control: no-cache
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Date: Mon, 13 Feb 2017 11:46:16 GMT
Set-Cookie: csrf_token=random_string; expires=Sat, 12-Feb-2022 11:46:16 GMT; Max-Age=157680000; path=/; domain=http://backend.test; HttpOnly

但是,当我转到http://backend.test Url 时,没有设置 cookie(控制台中的 document.cookie 返回 null)。 后端也看不到 cookie:dd($request->cookie("csrf_token") 返回 null。

即使我们省略域,它也不起作用。有什么想法吗?

【问题讨论】:

    标签: angularjs laravel cookies laravel-5.3 csrf


    【解决方案1】:

    当你使用 Laravel 时,你不必自己设置 csrf cookie。 Laravel 会自动为你完成这项工作。

    所以 laravel 会自动创建一个 cookie 来存储 csrf 令牌。该 cookie 的名称是“XSRF-TOKEN”。

    【讨论】:

    • 我们有两个不同的服务器:一个后端服务器(使用 laravel)和一个前端服务器(使用 angularjs)。因此,通常 laravel 自动完成的这项工作不适用于我们的架构。
    【解决方案2】:

    要让 Angular 在 CORS(跨源资源共享请求)中随请求一起发送 cookie,您需要在配置中设置 $httpProvider 作为依赖项注入:

    .config(function ($httpProvider) {
        $httpProvider.defaults.withCredentials = true;
        //rest of route code
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-12
      • 1970-01-01
      • 2020-08-16
      • 1970-01-01
      • 2017-07-08
      相关资源
      最近更新 更多