我试图让我的用户登录后通过Javasscript使用我自己的API,https://laravel.com/docs/5.7/passport#consuming-your-api-with-javascript
我已经安装了Passport。我的网络中间件定义为
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Barryvdh\Cors\HandleCors::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\SetLocale::class,
\Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],
我看到登录后似乎确实创建了一个“ laravel_token” cookie。
然后我尝试向API路由发送简单的get请求
window.$.ajax({
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'GET',
url: 'https://mywebsite.test/api/testApi',
success: function (response) {
console.log(response);
},
error: function (xhr) {
console.error(xhr.responseText);
}
});
我唯一得到的答复是
{"message":"Unauthenticated."}
我想念什么?
更新
该请求是从子域client.mywebsite.test执行的,经过调查,这似乎是问题所在。从mywebsite.test执行ajax调用时,身份验证工作良好。如何为子域修复该问题?
从子域请求时请求标头:
OPTIONS /api/testApi HTTP/1.1
Host: mywebsite.test
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: https://client.mywebsite.test
Access-Control-Request-Headers: x-csrf-token,x-requested-with
Accept: */*
Referer: https://client.mywebsite.test/home
从域请求时请求标头:
GET /api/testApi HTTP/1.1
Host: mywebsite.test
Connection: keep-alive
X-CSRF-TOKEN: fLTkaq9p62FROutzch2iE9IF864al8adFnxptbve
X-Requested-With: XMLHttpRequest
Cookie: laravel_token=[...]; XSRF-TOKEN=[...]; mywebsite_session=[...];
答案 0 :(得分:0)
这在Laravel 5.6项目中对我有用:
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected static $serialize = true;
/**
* The names of the cookies that should not be encrypted.
*
* @var array
*/
protected $except = [
//
];
}
在$serialize
中间件上将属性true
设置为EncryptCookies
。
答案 1 :(得分:0)
浏览后浏览和浏览。
事实证明,问题确实出在Cookie没有与CORS请求一起发送的情况下。我通过在Ajax调用中添加“ withCredentials”来解决该问题:
window.$.ajax({
headers: {
'Accept': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
xhrFields: {
withCredentials: true
},
type: 'GET',
url: 'https://mywebsite.test/api/testApi',
success: function (response) {
console.log(response);
},
error: function (xhr) {
console.error(xhr.responseText);
}
});
您还需要确保响应的标头指定接受凭据:
header('Access-Control-Allow-Credentials: true');