Installation
composer require awuniversity/oauth2-aw
Ensure awuniversity/oauth2-aw is added to providers in config/app.php:
'providers' => [
// ...
AWUniversity\OAuth2\AWServiceProvider::class,
],
Publish Config
php artisan vendor:publish --provider="AWUniversity\OAuth2\AWServiceProvider" --tag="config"
Update config/services/aw.php with your client ID, client secret, and redirect URI.
Add Route
Route::get('/login/aw', [AuthController::class, 'redirectToAW']);
Route::get('/login/aw/callback', [AuthController::class, 'handleAWCallback']);
First Use Case
Use the AW facade to fetch user data after authentication:
use AWUniversity\OAuth2\Facades\AW;
$user = AW::user(); // Returns authenticated user data
Redirect to AW
public function redirectToAW()
{
return AW::authorize(['email', 'profile']); // Request scopes
}
Handle Callback
public function handleAWCallback()
{
$user = AW::user(); // Hydrates user data from token
auth()->loginUsingId($user['id']); // Integrate with Laravel auth
}
Fetch Specific Fields
$email = AW::user()->email;
$name = AW::user()->name;
Refresh Token
AW::refreshToken(); // Extends session if token expires
Middleware for Protected Routes
Route::middleware(['auth:aw'])->group(function () {
// Routes requiring AW auth
});
Register middleware in app/Http/Kernel.php:
'aw' => \AWUniversity\OAuth2\Middleware\AuthenticateWithAW::class,
Custom User Model
Extend AWUser or map fields to your User model:
AW::setUserModel(User::class);
AW::mapUserFields([
'email' => 'aw_email',
'name' => 'aw_name',
]);
Token Expiry
try-catch for AW::user():
try {
$user = AW::user();
} catch (\League\OAuth2\Client\Provider\Exception\TokenExpiredException $e) {
AW::refreshToken();
$user = AW::user();
}
Scope Mismatch
AW::user() returns null, verify scopes in authorize() match the provider’s API requirements.State Validation
state parameter in callbacks to prevent CSRF:
if (!hash_equals(session('oauth_state'), $request->state)) {
throw new \Exception('State mismatch');
}
Enable Logging
Add to config/services/aw.php:
'logging' => true,
Check storage/logs/laravel.log for OAuth2 errors.
Token Inspection Dump the raw token response:
$token = AW::getAccessToken();
dd($token->getValues());
Custom Provider Extend the default provider by binding a custom one:
AW::setProvider(new \AWUniversity\OAuth2\Provider\CustomAWProvider());
Webhook Listeners
Use Laravel’s Event facade to listen for AW OAuth events:
Event::listen(\AWUniversity\OAuth2\Events\TokenRefreshed::class, function () {
// Handle refreshed token
});
Rate Limiting Implement middleware to throttle AW API calls:
Route::middleware(['throttle:60,1'])->group(function () {
// Rate-limited routes
});
Redirect URI
Must match exactly (including http/https) in both config/services/aw.php and the AW provider dashboard.
Caching Tokens Disable caching for development:
'cache_tokens' => env('APP_ENV') !== 'local',
How can I help you explore Laravel packages today?