在laravel里使用get请求调用/sanctum/csrf-cookie的时候,都经历了什么?
背景:
get请求/sanctum/csrf-cookie,常用于登录,代码如下:
return this.http.get<any>(this.apiURL + ':' + this.port + '/sanctum/csrf-cookie', { withCredentials: true }) .pipe( switchMap(result => this.http.post<object>(this.apiURL + ':' + this.port + '/api/login', user)), retry(1), catchError(this.handleError) );
为什么要这样?这个过程又经历了什么呢?下面将逐步展开分析。
一、withCredentials: true 是做什么的?
二、get请求到了/sanctum/csrf-cookie,经历了什么?
laravel的/sanctum/csrf-cookie路由,定义在src/SanctumServiceProvider.php
protected function defineRoutes() { if (app()->routesAreCached() || config('sanctum.routes') === false) { return; } Route::group(['prefix' => config('sanctum.prefix', 'sanctum')], function () { Route::get( '/csrf-cookie', CsrfCookieController::class.'@show' )->middleware('web'); }); }
在这里,做了2件事:
1.为/sanctum/csrf-cookie指明了要使用的控制器及其方法,CsrfCookieController::class.'@show'
2.指定了要使用的middleware中间件,即:web,那么,web中间件是做什么的呢?
web中间件位于app/Http/Kernel.php的$middlewareGroups,web中间件由下列组件组成:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Laravel\Jetstream\Http\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\HandleInertiaRequests::class,
],
'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
从web中间件的组成组件来大概推断,web中间件会做下列事情:
1.加密cookie
2.把cookie添加到队列并响应给Response
3.开启session
4.验证session
5.共享来自session的错误信息
6.验证csrf token
7.替代绑定
8.处理inertia的request请求