PHP code example of impression / laravel-google-passport-oauth

1. Go to this page and download the library: Download impression/laravel-google-passport-oauth library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

impression / laravel-google-passport-oauth example snippets


Schema::table('users', function (Blueprint $table) {
    $table->string('google_id')->nullable()->unique();
});

use Impression\GooglePassportOAuth\Http\Controllers\MCPTokenController;
use Impression\GooglePassportOAuth\Http\Controllers\MCPConfirmController;
use Impression\GooglePassportOAuth\Http\Controllers\MCPConnectionController;
use Impression\GooglePassportOAuth\Http\Middleware\EnsureOAuthAuthenticated;

Route::middleware(['throttle:60,1', EnsureOAuthAuthenticated::class])->group(function () {
    // Exchange auth token for Passport token (Google or fallback parent app auth)
    Route::post('/oauth/mcp/token', [MCPTokenController::class, 'exchange']);
    
    // Show confirmation page with existing connections
    Route::get('/oauth/mcp/confirm', [MCPConfirmController::class, 'show']);
    
    // Register new MCP OAuth connection
    Route::post('/oauth/mcp/connections', [MCPConnectionController::class, 'store']);
});

return [
    // Google OAuth credentials (from Google Cloud Console)
    'google_client_id' => env('GOOGLE_OAUTH_CLIENT_ID'),
    'google_client_secret' => env('GOOGLE_OAUTH_CLIENT_SECRET'),
    
    // Which user model to query for authentication
    'user_model' => env('GOOGLE_OAUTH_USER_MODEL', 'App\Models\User'),
    
    // Column mapping for flexible schema
    'column_mapping' => [
        'email' => env('GOOGLE_OAUTH_EMAIL_COLUMN', 'email'),
        'google_id' => env('GOOGLE_OAUTH_GOOGLE_ID_COLUMN', 'google_id'),
    ],
    
    // Whitelist by domain (null = allow all domains)
    'domain_whitelist' => env('GOOGLE_OAUTH_DOMAIN_WHITELIST') 
        ? explode(',', env('GOOGLE_OAUTH_DOMAIN_WHITELIST'))
        : null,
    
    // Passport token expiry (seconds)
    'token_expires_in' => env('GOOGLE_OAUTH_TOKEN_EXPIRES_IN', 31536000), // 1 year
    
    // MCP OAuth 2.1 Registry configuration
    'mcp_registry' => [
        'parent_app_guard' => env('MCP_OAUTH_PARENT_GUARD', 'web'),
        'discovery_endpoint' => env('MCP_OAUTH_DISCOVERY_ENDPOINT', '/oauth/mcp/discovery'),
        'issuer_url' => env('MCP_OAUTH_ISSUER_URL'),
    ],

Route::name('mcp.')->prefix('oauth')->group(function () {
    // Google OAuth endpoint (existing)
    Route::post('google-token', [\Impression\GooglePassportOAuth\Http\Controllers\GoogleTokenController::class, 'exchange'])
        ->middleware('throttle:60,1');

    // MCP OAuth 2.1 endpoints (new)
    Route::middleware(['throttle:60,1', \Impression\GooglePassportOAuth\Http\Middleware\EnsureOAuthAuthenticated::class])
        ->group(function () {
            Route::post('mcp/token', [\Impression\GooglePassportOAuth\Http\Controllers\MCPTokenController::class, 'exchange']);
            Route::get('mcp/confirm', [\Impression\GooglePassportOAuth\Http\Controllers\MCPConfirmController::class, 'show']);
            Route::post('mcp/connections', [\Impression\GooglePassportOAuth\Http\Controllers\MCPConnectionController::class, 'store']);
        });
});

use Impression\GooglePassportOAuth\Models\MCPOAuthConnection;

// Get all active connections for a user
$connections = MCPOAuthConnection::where('user_id', $user->id)->active()->get();

// Find a specific connection
$connection = MCPOAuthConnection::findOrFail($id);

// Update connection status
$connection->update(['status' => 'inactive']);

User::create([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'google_id' => 'google-user-id-123',  // optional, from Google tokeninfo
    'password' => Hash::make(Str::random(32)), // optional, can be dummy
]);

'column_mapping' => ['email' => 'email', 'google_id' => 'google_user_id'],
'domain_whitelist' => ['company.com'],

'column_mapping' => ['email' => 'work_email', 'google_id' => 'gid'],
'domain_whitelist' => ['company.com', 'internal.company.com'],

'column_mapping' => ['email' => 'contact_email', 'google_id' => null],
'domain_whitelist' => ['partner1.com', 'partner2.com'],

use Illuminate\Support\Facades\Http;

public function test_google_oauth_integration()
{
    Http::fake([
        'https://www.googleapis.com/oauth2/v3/tokeninfo' => Http::response([
            'email' => '[email protected]',
            'user_id' => 'google-123',
            'expires_in' => 3600,
        ]),
    ]);
    
    // Create user
    $user = User::factory()->create(['email' => '[email protected]']);
    
    // Exchange token
    $response = $this->postJson('/oauth/google-token', [
        'access_token' => 'test-token',
    ]);
    
    $response->assertStatus(200)
        ->assertJsonStructure(['access_token', 'token_type', 'expires_in']);
}

use Impression\GooglePassportOAuth\Services\GoogleTokenValidator;

$validator = app(GoogleTokenValidator::class);

// Validate token (with optional refresh)
$tokenInfo = $validator->validate('access-token', 'refresh-token');

// Returns:
// [
//     'email' => '[email protected]',
//     'name' => '[email protected]',
//     'google_id' => 'google-123',
//     'expires_at' => Carbon instance,
// ]

use Impression\GooglePassportOAuth\Services\UserSyncResolver;

$resolver = app(UserSyncResolver::class);

// Resolve user (throws if not found or domain not allowed)
$user = $resolver->resolveByEmail('[email protected]');

use Impression\GooglePassportOAuth\Exceptions\{
    InvalidTokenException,
    TokenExpiredException,
    RefreshFailedException,
    GoogleApiException,
    UserNotFoundByEmailException,
    DomainNotAllowedException,
};
bash
php artisan vendor:publish --provider="Impression\GooglePassportOAuth\GoogleOAuthServiceProvider" --tag="google-oauth-config"
bash
php artisan migrate
bash
php artisan vendor:publish --provider="Impression\GooglePassportOAuth\GoogleOAuthServiceProvider" --tag="google-oauth-migrations"
bash
php artisan migrate
bash
composer vendor:publish --provider="Impression\GooglePassportOAuth\GoogleOAuthServiceProvider" --tag="google-oauth-config"
php artisan vendor:publish --provider="Impression\GooglePassportOAuth\GoogleOAuthServiceProvider" --tag="google-oauth-migrations"
php artisan migrate