Since this is a Symfony bundle, direct Laravel integration requires Symfony Bridge or a wrapper. Use symfony/bridge or laravel/symfony-finder for compatibility.
Install via Composer (Symfony-only, but adaptable):
composer require cpj/cpjFOSOAuthServerBundle
For Laravel, create a custom wrapper or use a Symfony microkernel (e.g., symfony/console).
First Use Case: OAuth2 Authorization Server
config/routes.yaml (Symfony) or Laravel’s routes/web.php (via a Symfony component proxy).# Symfony
fos_oauth_server_token:
resource: "@FOSOAuthServerBundle/Resources/config/routing/token.xml"
prefix: /oauth/v2
Route::get('/oauth/v2/token', [OAuthController::class, 'token']);
Key Files to Review
Resources/doc/index.md (official docs).Resources/config/routing/token.xml (endpoint definitions).DependencyInjection/Configuration.php (bundle config).Symfony-Laravel Bridge
use Symfony\Component\HttpKernel\Kernel;
use Cpj\FOSOAuthServerBundle\CpjFOSOAuthServerBundle;
class OAuthServiceProvider extends ServiceProvider {
public function register() {
$kernel = new Kernel(env('APP_ENV'), false);
$kernel->boot();
$kernel->getContainer()->register(new CpjFOSOAuthServerBundle(), true);
}
}
Client & Grant Management
fos_oauth_server.client service or a Laravel facade:
// Symfony (adapt to Laravel)
$clientManager = $this->get('fos_oauth_server.client_manager');
$client = $clientManager->createClient();
$client->setRandomId();
$client->setSecret('secret');
$clientManager->updateClient($client);
authorization_code, password, or client_credentials via config:
# config/packages/fos_oauth_server.yaml (Symfony)
fos_oauth_server:
grants:
- authorization_code
- password
Token Generation & Validation
fos_oauth_server.token_storage service to issue/validate tokens:
$tokenStorage = $this->get('fos_oauth_server.token_storage');
$token = $tokenStorage->createAccessToken($client, $user, ['scope' => 'read']);
trait OAuthHelper {
public function issueToken(User $user, Client $client) {
return app('fos_oauth_server.token_storage')->createAccessToken($client, $user, ['scope' => 'read']);
}
}
Resource Server Integration
Route::get('/api/data', function () {
$token = request()->bearerToken();
$validator = $this->get('fos_oauth_server.token_validator');
if (!$validator->validateToken($token)) {
abort(401);
}
return response()->json(['data' => 'protected']);
})->middleware('auth:api');
Symfony Dependency Hell
HttpFoundation, Security, and DependencyInjection. In Laravel:
SecurityContext with Laravel’s Auth facade:
$security = new SymfonySecurityContext(app('auth')->user());
$this->get('fos_oauth_server.security.token_storage')->setToken($security->getToken());
Token Storage Backend
# config/packages/fos_oauth_server.yaml
fos_oauth_server:
token_storage:
class: Cpj\FOSOAuthServerBundle\Storage\DoctrineOAuthTokenStorage
entity: App\Entity\OAuthToken
OAuthTokenStorageInterface.CSRF & State Management
fos_oauth_server.authorization uses CSRF tokens. In Laravel:
Route::post('/oauth/v2/auth', function () {
if (!hash_equals(session('oauth_state'), request('state'))) {
abort(403);
}
// Proceed with auth.
});
CORS Headers
OAuth2Response. Configure CORS explicitly:
Header::set('Access-Control-Allow-Origin', '*');
Header::set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
Enable Verbose Logging
Add to config/packages/monolog.yaml (Symfony) or Laravel’s config/logging.php:
handlers:
oauth:
type: stream
path: "%kernel.logs_dir%/oauth.log"
level: debug
Token Validation Errors Common issues:
invalid_grant: Check client credentials or grant type.invalid_scope: Verify scopes in fos_oauth_server.scopes config.expired_token: Ensure token TTL is set in storage backend.Database Schema Mismatch Run Symfony’s migrations (adapted for Laravel):
php bin/console doctrine:migrations:execute --query="CREATE TABLE oauth_token (id INT AUTO_INCREMENT PRIMARY KEY, ...)"
Custom Grant Types
Extend OAuthGrantType:
class CustomGrant extends AbstractGrant {
public function getName() { return 'custom_grant'; }
protected function validateGrant($grant) { /* ... */ }
}
Register in config:
fos_oauth_server:
grants:
- custom_grant
User Provider Integration
Override Symfony’s UserProvider to use Laravel’s User model:
class LaravelUserProvider implements UserProviderInterface {
public function loadUserByUsername($username) {
return User::where('email', $username)->first();
}
}
Bind in services:
services:
fos_oauth_server.user_provider:
class: App\Service\LaravelUserProvider
API Rate Limiting
Combine with Laravel’s throttle middleware:
Route::middleware(['throttle:60,1', 'oauth'])->get('/api/rate-limited');
How can I help you explore Laravel packages today?