環境
Laravel v9.5.1 (PHP v8.1.3)
状況
Socialiteを使ってGoogleログイン機能を実装し、デプロイ後/auth/google/redirect
にアクセスした際下記のエラー。
RuntimeException
Session store not set on request.
api.php
Route::get('auth/google/redirect', function () {
return Socialite::driver('google')->redirect();
});
Route::get('auth/google/callback', [OAuthController::class, 'authGoogleCallback']);
解決法
web.php
にルーティングを記載する。
Socialite
はセッション認証なのでapi.php
ではなくてweb.php
に記載しないと動かない。
web.php
Route::get('auth/google/redirect', function () {
return Socialite::driver('google')->redirect();
});
Route::get('auth/google/callback', [OAuthController::class, 'authGoogleCallback']);
web.phpとapi.phpの違い
api.phpにはVerifyCsrfToken
ミドルウェアがないので動かなかった。
app/Http/Kernel.php
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
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' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
参考