Laravel Socialite: InvalidStateException
The InvalidStateException is thrown by Laravel's Socialite package when the state parameter provided in the OAuth redirect URL does not match the one stored in the session.
The InvalidStateException is thrown by Laravel's Socialite package when the state parameter provided in the OAuth redirect URL does not match the one stored in the session. This is usually caused by one of the following reasons:
- The user has manually changed the state parameter in the redirect URL.
- The user has opened the OAuth redirect URL in a different browser or tab.
- The user has closed the browser or tab before being redirected back to your application.
- The session data has been lost or tampered with before the user was redirected back to your application.
To fix this issue, follow these steps:
- Verify session configuration: Check
config/session.phpto ensure the lifetime is sufficient for the OAuth flow. A short lifetime causes the state to expire before the callback returns.// config/session.php 'lifetime' => env('SESSION_LIFETIME', 120), 'expire_on_close' => false, - Clarify state parameter handling: Laravel Socialite automatically generates and stores the state parameter when you call
Socialite::driver('provider')->redirect(). If you are manually constructing the OAuth URL, you must manually generate a secure state string, store it in the session, and append it to the authorization URL. - Check callback configuration: Ensure the
redirectURL inconfig/services.phpexactly matches the callback URL registered in your OAuth provider's dashboard.// config/services.php 'github' => [ 'client_id' => env('GITHUB_CLIENT_ID'), 'client_secret' => env('GITHUB_CLIENT_SECRET'), 'redirect' => 'https://your-app.test/auth/github/callback', ], - Handle the exception gracefully: Wrap your Socialite callback in a
try-catchblock to catchInvalidStateExceptionand redirect the user back to login or display a friendly error.use Laravel\Socialite\Facades\Socialite; use Laravel\Socialite\Two\InvalidStateException; public function handleProviderCallback() { try { $user = Socialite::driver('github')->user(); // Handle user... } catch (InvalidStateException $e) { return redirect()->route('login')->with('error', 'Authentication failed. Please try again.'); } } - Debug step-by-step: If the issue persists, clear your browser's cookies for the application domain, verify that
SESSION_DRIVERis set tofileordatabase(notarrayin production), and check your web server's proxy settings for cookie stripping.