Since this bundle is Symfony-based, Laravel developers must use a bridge like symfony/bridge or manually adapt it. Start by:
Install via Composer (adapted for Laravel):
composer require bshaffer/oauth2-server-bundle
Register the Bundle (in config/app.php):
'providers' => [
// ...
Symfony\Bridge\Laravel\ServiceProvider::class,
Bshaffer\OAuth2ServerBundle\OAuth2ServerBundle::class,
],
Publish Config (adapted for Laravel):
php artisan vendor:publish --provider="Bshaffer\OAuth2ServerBundle\OAuth2ServerBundle" --tag=config
Update config/oauth2.php with your database/grant type settings.
Define Routes (in routes/api.php):
Route::post('/token', 'OAuth2Controller@token')->name('oauth2.token');
First Use Case: Test with curl:
curl -X POST -H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_SECRET" \
http://your-app.test/token
Token Generation:
OAuth2Controller to handle /token requests. Extend handleTokenRequest() to customize logic:
public function token(Request $request)
{
$server = app('oauth2.server');
$server->addGrantType(app('oauth2.grant_type.authorization_code'));
return $server->handleTokenRequest($request, app('oauth2.response'));
}
Grant Type Restrictions:
// Example: Restrict to 'authorization_code' only
$server->setGrantType('authorization_code', true);
$server->setGrantType('password', false);
User Authentication:
user_credentials grant, implement a custom UserAuthenticationProvider:
use Bshaffer\OAuth2ServerBundle\Provider\UserAuthenticationProviderInterface;
class CustomUserAuth implements UserAuthenticationProviderInterface {
public function authenticate($username, $password) {
return User::where('email', $username)->first(); // Adapt to Laravel
}
}
Register it in config/oauth2.php:
'user_authentication_provider' => CustomUserAuth::class,
Scopes and Permissions:
Gate or Policy system to validate scopes:
// In a middleware or controller
if (!$server->validateScope('read:data')) {
throw new \Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException();
}
Token Storage:
OAuth2AccessToken model):
// Example: Extend the model to use Laravel's Eloquent
class OAuth2AccessToken extends \Bshaffer\OAuth2ServerBundle\Entity\OAuth2AccessToken {
use \Illuminate\Database\Eloquent\Model;
}
Symfony-Laravel Integration:
Container vs. Laravel’s ServiceProvider conflicts.Symfony\Bridge\Laravel\ServiceProvider and alias services in config/app.php:
'aliases' => [
'oauth2.server' => \Bshaffer\OAuth2ServerBundle\OAuth2Server::class,
],
Database Schema Mismatch:
oauth2_client, oauth2_access_token). Laravel’s migrations may conflict.Schema::create('oauth2_client', function (Blueprint $table) {
$table->id();
$table->string('random_id')->unique();
$table->string('client_secret');
$table->string('redirect_uri')->nullable();
// ... other fields
});
Grant Type Misconfiguration:
unsupported_grant_type.config/oauth2.php and ensure the grant type is enabled:
'grant_types' => ['authorization_code', 'client_credentials'], // Explicitly list allowed grants
CSRF Protection:
/token endpoint may block POST requests due to Laravel’s CSRF middleware.app/Http/Middleware/VerifyCsrfToken.php:
protected $except = [
'oauth2.token',
];
Enable Verbose Logging:
config/oauth2.php:
'debug' => env('APP_DEBUG', false),
storage/logs/laravel.log.Token Validation:
OAuth2 facade to validate tokens in API middleware:
use Bshaffer\OAuth2ServerBundle\OAuth2;
public function handle($request, Closure $next) {
$server = OAuth2::server();
$request->oauth2 = $server->validateAuthenticatedRequest($request);
return $next($request);
}
Testing with Postman:
Authorization Code flow:
GET /authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI.POST /token with grant_type=authorization_code.Custom Storage:
OAuth2AccessTokenRepositoryInterface to use Laravel’s Eloquent:
class EloquentTokenRepository implements OAuth2AccessTokenRepositoryInterface {
public function getNewToken($clientId, $userId, array $scopes, $grantType) {
return OAuth2AccessToken::create([...]);
}
}
Register it in config/oauth2.php:
'access_token_repository' => EloquentTokenRepository::class,
Custom Responses:
OAuth2Response to modify error messages or add custom fields:
class CustomResponse extends \Bshaffer\OAuth2ServerBundle\Response\OAuth2Response {
public function setError($error, $errorDescription, array $additionalInformation = []) {
$additionalInformation['custom_field'] = 'value';
return parent::setError($error, $errorDescription, $additionalInformation);
}
}
Event Listeners:
oauth2.token_generated) via Laravel’s events:
Event::listen('oauth2.token_generated', function ($token) {
// Log or process token generation
});
How can I help you explore Laravel packages today?