尽管设置了Cookie,但Laravel Cookie仍未设置

问题描述:

我们正在开发一个带有REST API的网站(AngularJS 1.6.1中的前端,Laravel 5.3中的后端)。 为了增加CSRF保护,我们的后端需要用随机字符串在客户端设置一个后端cookie。在laravel中,我们返回这个响应: response(“OK”,200) - > cookie(“csrf_token”,“random_string”);尽管设置了Cookie,但Laravel Cookie仍未设置

的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网址,没有Cookie设置(document.cookie中在控制台返回null)。 后端无法看到的cookie或者:DD($请求 - >饼干(“csrf_token”)返回null

如果我们忽略域,它甚至没有工作,任何想法

对于Angular在CORS(跨源资源共享请求)中发送cookie以及请求,您需要se T,与$httpProvider你的配置注入的依赖性:

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

当您使用。? Laravel不需要自己设置csrf cookie,Laravel自动为你做这个工作

所以laravel自动创建一个cookie来存储csrf标记,该cookie的名字是“XSRF-TOKEN”。

+0

我们有两种不同的服务器:后端服务器(与laravel)和前端服务器(与angularjs)。所以这个通常会自动执行的工作并不适用于我们的架构。 – Finn87