Laravel Passport is a package that provides a full OAuth2 server implementation for your Laravel application. It makes it easy to set up OAuth2 authentication in your Laravel API. Below are the steps to configure and use Laravel Passport for OAuth2 authentication:
To install Passport, run the following Composer command:
bashcomposer require laravel/passport
Run the migration command to create the necessary tables for Passport:
bashphp artisan migrate
Next, install Passport using the passport:install
Artisan command. This command will create the encryption keys needed to generate secure access tokens:
bashphp artisan passport:install
In your AuthServiceProvider
(located at app/Providers/AuthServiceProvider.php
), add the following lines to the boot
method:
phpuse Laravel\Passport\Passport;
public function boot()
{
$this->registerPolicies(); Passport::routes();
}
In your User
model (usually located at app/User.php
), implement the HasApiTokens
trait:
phpuse Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
In your config/auth.php
file, make sure the api
driver is set to passport
:
php'guards' => [
'api' => [
'driver' => 'passport',
'provider' => 'users',
],
],
After completing the setup, run your Laravel application:
bashphp artisan serve
Now, you can define routes for handling OAuth2 authentication. Typically, this involves creating routes for login, registration, and accessing protected resources.
To obtain an access token, you need to send a POST request to the /oauth/token
endpoint with the client credentials and user credentials.
Use Passport's auth:api
middleware to protect routes that require authentication. Apply the middleware to your API routes:
phpRoute::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
That's it! You've now set up Laravel Passport for OAuth2 authentication in your Laravel application. Make sure to refer to the official Laravel Passport documentation for more detailed information and advanced configurations: Laravel Passport Documentation.
=== Happy Coding :)