ekreative/oauth2-symfony-bundle
Installation Add the package via Composer:
composer require ekreative/oauth2-symfony-bundle
Register the bundle in config/bundles.php:
Ekreative\OAuth2Bundle\OAuth2Bundle::class => ['all' => true],
Configuration Publish the default config:
php artisan vendor:publish --tag=oauth2-config
Update config/oauth2.php with your OAuth2 provider details (e.g., client ID, secret, authorization URL).
First Use Case: Authentication
Use the bundle’s Authenticator service to handle OAuth2 flows:
use Ekreative\OAuth2Bundle\Service\Authenticator;
class OAuthController extends Controller
{
public function redirectToProvider(Authenticator $authenticator)
{
return $authenticator->redirectToProvider();
}
public function handleProviderCallback(Authenticator $authenticator, Request $request)
{
$user = $authenticator->handleProviderCallback($request);
// Store user in session or create a Laravel user.
}
}
Authorization Code Flow (Recommended)
$authenticator->redirectToProvider('authorization_code');
$user = $authenticator->handleProviderCallback($request);
Resource Owner Password Credentials Flow For trusted clients (e.g., mobile apps):
$token = $authenticator->getAccessToken('password', [
'username' => 'user@example.com',
'password' => 'password',
]);
Token Storage
Use the TokenStorage service to persist/retieve tokens:
$tokenStorage->store($token);
$storedToken = $tokenStorage->getAccessToken();
Laravel-Specific Adaptations
Extend the bundle’s UserProvider to integrate with Laravel’s Auth system:
use Ekreative\OAuth2Bundle\Security\User\UserProviderInterface;
class LaravelUserProvider implements UserProviderInterface
{
public function loadUserByOAuthUserInfo($username, array $info)
{
return User::where('email', $username)->first();
}
}
Register it in config/oauth2.php under user_provider.
Middleware for Protected Routes
Use Symfony’s Firewall concept via Laravel’s middleware:
class OAuthMiddleware
{
public function handle($request, Closure $next)
{
if (!$request->user()) {
return redirect()->route('oauth.redirect');
}
return $next($request);
}
}
Custom Grant Types
Extend the GrantType class to support non-standard flows:
use Ekreative\OAuth2Bundle\GrantType\GrantTypeInterface;
class CustomGrantType implements GrantTypeInterface
{
public function getName() { return 'custom'; }
public function validate(array $params) { /* ... */ }
}
Register it in config/oauth2.php under grant_types.
In-Memory Token Storage
The default in_memory driver is not persistent. Switch to orm for production:
'driver' => 'orm',
Ensure your AccessToken entity extends Ekreative\OAuth2Bundle\Model\AccessTokenEntity.
CSRF Token Mismatch Symfony’s CSRF protection may conflict with OAuth2 redirects. Disable it for OAuth routes:
// In routes/web.php
Route::get('/oauth/callback', [OAuthController::class, 'handleCallback'])
->middleware('web')->withoutMiddleware(\App\Http\Middleware\VerifyCsrfToken::class);
State Parameter Handling
Always validate the state parameter in callbacks to prevent CSRF:
$authenticator->setState($request->session()->get('oauth_state'));
Provider-Specific Quirks
Some providers (e.g., Google) require additional scopes or parameters. Check their docs and adjust config/oauth2.php:
'providers' => [
'google' => [
'authorization_url' => 'https://accounts.google.com/o/oauth2/auth',
'access_token_url' => 'https://oauth2.googleapis.com/token',
'scope' => ['email', 'profile', 'https://www.googleapis.com/auth/userinfo.profile'],
],
],
Enable Debug Mode
Set 'debug' => true in config/oauth2.php to log OAuth2 requests/responses.
Token Validation
Use the TokenValidator service to manually validate tokens:
$validator = $container->get('oauth2.token_validator');
$isValid = $validator->validate($token);
Common Errors
invalid_grant: Check credentials or token expiration.redirect_uri_mismatch: Ensure the callback URL matches the registered one.unsupported_grant_type: Verify the grant type is supported by the provider.Custom User Entity
Extend the default UserEntity to add fields:
use Ekreative\OAuth2Bundle\Model\UserEntity as BaseUserEntity;
class CustomUserEntity extends BaseUserEntity
{
protected $avatarUrl;
// Add getters/setters.
}
Update config/oauth2.php:
'model' => [
'user' => App\Entity\CustomUserEntity::class,
],
Event Listeners
Listen to OAuth2 events (e.g., oauth2.token_created):
use Ekreative\OAuth2Bundle\Event\TokenEvent;
$dispatcher->addListener('oauth2.token_created', function (TokenEvent $event) {
// Log or process the token.
});
API Resource Server
Use the bundle’s ResourceServer to validate access tokens for API requests:
$resourceServer = $container->get('oauth2.resource_server');
$isValid = $resourceServer->validateRequest($request);
How can I help you explore Laravel packages today?