Laravel Sanctum Angular Authentication 419 error code



我正在尝试设置一个身份验证系统,使用Laravel Sanctum和Fortify作为后端,使用Angular作为前端。

前端运行在localhost:4200
后端运行在localhost:8000

我按照本教程查找常见错误,并相应地设置.env文件它看起来像这样:
SESSION_DRIVER=file
SESSION_LIFETIME=120
SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:4200
FRONTEND_URL=http://localhost:4200

和我的cors.php配置:

<?php
return [

'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:4200')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];

为了登录我的用户,我使用了这个angular服务函数:

options = {
headers: new HttpHeaders({
Accept: 'application/json',
}),
withCredentials: true,
}
login(email: string, password: string): Observable<any> {
return this.http
.get(this.baseUrl + '/sanctum/csrf-cookie', this.options)
.pipe(
switchMap(() =>
this.http.post(
this.baseUrl + '/login',
{ email, password },
this.options
)
)
);
}

问题是,当我尝试登录时,我得到一个419错误代码,说CSRF令牌不匹配。

查看浏览器控制台中的cookie列表为空,因此即使对/csrf-cookie的请求成功也不会传递cookie

我哪里做错了她?是angular服务还是我的后端配置?

在询问了所有可能的来源后,我终于解决了这个问题,我们来谈谈:

看起来特别在MacOS上,如果你尝试从localhost:4200发送请求,Origin和Refero报头由于某种原因将不匹配Host报头

我解决了这个问题,改变了我的Laravel .env和配置文件中的每个localhost出现,然后在浏览器内转到127.0.0.1:4200,而不是localhost:4200

解释起来有点奇怪但它使请求到达相同的源即使localhost关键字默认表示127.0.0.1 IP

希望能帮到别人

最新更新