Authentication is a cornerstone of modern web applications. In Laravel, Passport provides a full OAuth2 server implementation, enabling API authentication seamlessly. This guide walks you through the entire process of setting up Laravel Passport, from installation to securing and testing your API.
Laravel Passport simplifies the complexities of OAuth2 authentication by integrating it tightly with Laravel's ecosystem. With Passport, you can:
Before diving in, ensure you have:
If you don’t have a project set up, create one with:
composer create-project --prefer-dist laravel/laravel passport-auth cd passport-auth
Run the following command to add Passport to your project:
composer require laravel/passport
Publish the Passport migrations and configuration files:
php artisan vendor:publish --tag=passport-migrations php artisan migrate
Run the installation command:
php artisan passport:install
This generates encryption keys and creates OAuth clients in your database. Make note of the output, especially the client IDs and secrets.
To create a personal access client explicitly, run:
php artisan passport:client --personal
Add the HasApiTokens trait to your user model:
use Laravel\Passport\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; // Other properties... }
Configure Passport as the driver for API guards in config/auth.php:
'guards' => [ 'api' => [ 'driver' => 'passport', 'provider' => 'users', ], ],
In AppProvidersAppServiceProvider, load Passport's routes:
use Laravel\Passport\Passport; public function boot(): void { Passport::routes(); Passport::tokensExpireIn(now()->addDays(15)); Passport::refreshTokensExpireIn(now()->addDays(30)); Passport::personalAccessTokensExpireIn(now()->addMonths(6)); }
Define API routes in routes/api.php:
use App\Http\Controllers\AuthController; Route::post('/register', [AuthController::class, 'register']); Route::post('/login', [AuthController::class, 'login']); Route::middleware('auth:api')->get('/user', [AuthController::class, 'user']);
Implement authentication methods:
composer create-project --prefer-dist laravel/laravel passport-auth cd passport-auth
Ensure secure access to Passport keys:
composer require laravel/passport
Verify permissions:
php artisan vendor:publish --tag=passport-migrations php artisan migrate
Expected output:
php artisan passport:install
Use Postman or any API client to test endpoints:
Congratulations! You've successfully implemented API authentication using Laravel Passport. This setup provides a robust foundation for securing your API. Explore advanced Passport features like scopes, token revocation, and client credentials to further enhance your application's security.
The above is the detailed content of Laravel Authentication Using Passport. For more information, please follow other related articles on the PHP Chinese website!