W3docs

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:

  1. The user has manually changed the state parameter in the redirect URL.
  2. The user has opened the OAuth redirect URL in a different browser or tab.
  3. The user has closed the browser or tab before being redirected back to your application.
  4. 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:

  1. Verify session configuration: Check config/session.php to 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,
  2. 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.
  3. Check callback configuration: Ensure the redirect URL in config/services.php exactly 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',
    ],
  4. Handle the exception gracefully: Wrap your Socialite callback in a try-catch block to catch InvalidStateException and 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.');
        }
    }
  5. Debug step-by-step: If the issue persists, clear your browser's cookies for the application domain, verify that SESSION_DRIVER is set to file or database (not array in production), and check your web server's proxy settings for cookie stripping.