所以花了几个小时,我什至无法通读并尝试互联网上可用的任何解决方案,也无法弄清问题。我正在将Laravel 7.x与Vue js结合使用,并在Sanctum SPA身份验证中苦苦挣扎。
Login请求工作正常,它使用在[[web.php中定义的Auth :: routes()
但是对在[[auth:sanctum中间件下的api.php中定义的API发出的任何请求均返回401。例如,获取用户对象的调用失败,状态为401:
这里是请求标题:
这是web.php
这是api.php
这里是sanctum.php
中的有状态
对象'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost,127.0.0.1,127.0.0.1:8000')),
在vue.js方面,我已将withCredentials标志设置为true:window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.withCredentials = true;
在
cors.php
中,suports_credentials标志也设置为true并且,这是我的Kernel.php
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:60,1',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];