Installation
composer require awuniversity/oauth2-client
Publish the config file (if needed):
php artisan vendor:publish --provider="AWUniversity\OAuth2Client\OAuth2ClientServiceProvider"
Configuration
Edit config/oauth2-client.php with your OAuth provider details (e.g., client ID, secret, redirect URI).
Example for a generic OAuth2 provider:
'providers' => [
'generic' => [
'client_id' => env('OAUTH_CLIENT_ID'),
'client_secret' => env('OAUTH_CLIENT_SECRET'),
'redirect' => env('OAUTH_REDIRECT_URI'),
'scope' => ['openid', 'email', 'profile'],
'authorize_url' => 'https://provider.com/oauth/authorize',
'access_token_url' => 'https://provider.com/oauth/token',
'user_info_url' => 'https://provider.com/api/user',
],
],
First Use Case: Authentication Flow Add a route to initiate OAuth:
Route::get('/login/{provider}', [OAuthController::class, 'redirectToProvider']);
Handle the callback:
Route::get('/login/{provider}/callback', [OAuthController::class, 'handleProviderCallback']);
Create a controller to manage the flow:
use AWUniversity\OAuth2Client\Facades\OAuth2Client;
public function redirectToProvider($provider)
{
return OAuth2Client::authorize($provider);
}
public function handleProviderCallback($provider)
{
$user = OAuth2Client::getUser($provider);
// Store user data in session/database and redirect.
}
User Authentication
OAuth2Client::authorize($provider) to redirect users to the OAuth provider.OAuth2Client::getUser($provider).User::updateOrCreate()).Token Management
$token = OAuth2Client::refreshToken($provider, $refreshToken);
API Integration
$response = OAuth2Client::get($provider, 'https://api.provider.com/data', [
'headers' => ['Authorization' => 'Bearer ' . $token],
]);
Multi-Provider Support
config/oauth2-client.php and switch dynamically:
$provider = request()->input('provider');
$user = OAuth2Client::getUser($provider);
Middleware: Protect routes with OAuth-verified users:
Route::middleware(['auth.oauth'])->group(function () {
// Protected routes
});
Define middleware in app/Http/Kernel.php:
'auth.oauth' => \AWUniversity\OAuth2Client\Http\Middleware\AuthenticateOAuth::class,
Events: Listen for OAuth events (e.g., OAuthUserFetched) to log or process user data:
Event::listen(OAuthUserFetched::class, function ($event) {
// Custom logic (e.g., sync with CRM)
});
Testing: Mock the OAuth provider in tests:
$this->mock(OAuth2Client::class)
->shouldReceive('getUser')
->andReturn(['id' => 123, 'email' => 'user@example.com']);
Deprecated Package
php-oauth2 if critical features are missing.Session Handling
SESSION_DRIVER is configured (e.g., file, database).php artisan session:clear
Provider-Specific Quirks
'providers' => [
'github' => [
'scope' => ['user:email', 'read:org'], // Custom scopes
],
],
CSRF Protection
APP_DEBUG=false in production to avoid CSRF token issues during redirects.config/oauth2-client.php:
'debug' => env('APP_DEBUG', false),
http vs https) cause callback failures.OAuth2Client::validateToken($provider, $token) to debug token issues.Custom User Mapping Override the default user mapping logic by binding a service provider:
OAuth2Client::extend('custom', function ($app) {
return new CustomOAuthProvider($app['config']['oauth2-client.providers.custom']);
});
Add Provider-Specific Logic
Extend the base OAuth2Client class or use facades to inject custom logic:
OAuth2Client::afterUserFetch(function ($user, $provider) {
if ($provider === 'google') {
$user['provider_metadata'] = $this->parseGoogleData($user);
}
});
API Client Customization Replace the underlying HTTP client (e.g., Guzzle) by binding a new instance:
$client = new \GuzzleHttp\Client(['timeout' => 30]);
OAuth2Client::setHttpClient($client);
How can I help you explore Laravel packages today?