lucadegasperi/oauth2-server-laravel
Installation:
composer require lucadegasperi/oauth2-server-laravel
Register the service provider in config/app.php:
'providers' => [
// ...
LucaDegasperi\OAuth2Server\OAuthServiceProvider::class,
],
Publish Config:
php artisan vendor:publish --provider="LucaDegasperi\OAuth2Server\OAuthServiceProvider"
Configure config/oauth2-server.php (e.g., set private_key_path, encryption_key, and grant_types).
First Use Case:
/oauth/authorize route with a client ID (e.g., http://your-app.test/oauth/authorize?client_id=test_client&redirect_uri=http://your-app.test/callback&response_type=code)./oauth/token (POST request with grant_type=authorization_code).config/oauth2-server.php (adjust encryption keys, storage, and grant types).app/Http/Middleware/OAuth2ServerMiddleware.php (for protecting routes).routes/web.php or routes/api.php (define /oauth/authorize, /oauth/token, etc.).Client Registration:
oauth_clients table (or your custom storage).php artisan vendor:publish --tag=migrations
php artisan migrate
Grant Types:
// In a controller:
$request = new \Laravel\Lumen\Http\Request();
$server = new \LucaDegasperi\OAuth2Server\OAuthServer($request);
$server->setStorageData('oauth_clients', $clientId);
$authRequest = $server->validateAuthorizationRequest();
$server->validateCredentials($username, $password);
$server->issueAccessToken();
Resource Server:
Route::group(['middleware' => 'oauth'], function () {
Route::get('/api/user', 'UserController@getUser');
});
$request = app('request');
$server = new \LucaDegasperi\OAuth2Server\OAuthServer($request);
$resourceOwner = $server->validateAuthenticatedRequest();
Custom Storage:
LucaDegasperi\OAuth2Server\Storage\StorageInterface for Eloquent or custom storage:
class CustomStorage implements StorageInterface {
public function getClient($clientId) {
return Client::where('id', $clientId)->first();
}
// Implement other methods...
}
AppServiceProvider:
$this->app->bind(
\LucaDegasperi\OAuth2Server\Storage\StorageInterface::class,
CustomStorage::class
);
OAuth2ServerMiddleware in $app->middleware()./oauth/token if using AJAX (e.g., with fruitcake/laravel-cors).config/oauth2-server.php:
'debug' => env('APP_DEBUG', false),
LucaDegasperi\OAuth2Server\Tests\TestCase as a base for PHPUnit tests.Deprecation Warning:
composer.json:
"lucadegasperi/oauth2-server-laravel": "2.0.0"
Storage Backend:
'storage' => [
'class' => \LucaDegasperi\OAuth2Server\Storage\DatabaseStorage::class,
'table_clients' => 'oauth_clients',
'table_access_tokens' => 'oauth_access_tokens',
'table_scopes' => 'oauth_scopes',
],
CSRF Issues:
/oauth/authorize endpoint requires CSRF protection. Add to VerifyCsrfToken middleware:
protected $except = [
'oauth/authorize',
];
Token Expiry:
'access_token_lifetime' => 3600, // 1 hour in seconds
Redirect URIs:
redirect_uri in client registration to prevent open redirects.Enable Debug Mode:
'debug' => true,
Check logs for detailed OAuth2 flow errors.
Common Errors:
invalid_request: Missing or malformed parameters (e.g., client_id, redirect_uri).invalid_client: Incorrect client ID/secret or unregistered client.unsupported_grant_type: Requested grant type not enabled in config.invalid_scope: Requested scope not configured for the client.Token Validation:
$server = new \LucaDegasperi\OAuth2Server\OAuthServer($request);
try {
$resourceOwner = $server->validateAuthenticatedRequest();
} catch (\League\OAuth2\Server\Exception\TokenExpiredException $e) {
// Handle expired token
}
Custom Grant Types:
\League\OAuth2\Server\Grant\GrantInterface and register in config:
'grants' => [
\League\OAuth2\Server\Grant\AuthorizationCodeGrant::class,
\League\OAuth2\Server\Grant\PasswordGrant::class,
\App\Grants\CustomGrant::class,
],
Scopes:
\League\OAuth2\Server\ScopeInterface and binding in AppServiceProvider:
$this->app->bind(
\League\OAuth2\Server\ScopeInterface::class,
\App\Scopes\CustomScope::class
);
Response Types:
'response_types' => ['code', 'token'], // Enable 'token' for implicit
Event Listeners:
access_token_created):
\Event::listen('oauth.access_token_created', function ($token) {
// Custom logic (e.g., log token creation)
});
How can I help you explore Laravel packages today?