In web application development, it is often necessary to use the OAuth2 protocol for user authentication and authorization so that users can use third-party services safely. By using Laravel Passport, you can easily handle the OAuth2 protocol to implement authentication and authorization in Laravel applications.
Laravel Passport is an open source software package that provides a complete OAuth2 server implementation, including Token generation, Token management, scope and other functions, making it very easy to implement the OAuth2 protocol in Laravel applications.
This article will introduce you how to use Laravel Passport to manage the OAuth2 protocol.
Before using the OAuth2 protocol, we need to generate an API key. The API key will be used as the OAuth2 client ID and secret and used to obtain the access token. We can generate API keys using the artisan command provided by Laravel Passport.
First, use composer to install Laravel Passport:
composer require laravel/passport
Then, run the migration command:
php artisan migrate
Next, use Passport’s client:secret
command Generate API Key:
php artisan passport:client --password
This will generate a client ID and a client secret.
After generating the API key, we need to configure the OAuth2 service. Laravel Passport provides some configuration options that can be configured by modifying the config/auth.php
file of your Laravel application.
In the auth.php
file, we need to set the api
driver to the Passport driver so that Laravel will use Passport to handle user authentication and authorization.
'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'passport', 'provider' => 'users', 'hash' => false, ], ],
Next, we need to create some OAuth2 routes in the application that will be used to handle OAuth2 requests. We can create these routes using the artisan command that automatically generates routes provided by Laravel Passport.
php artisan passport:routes
This will automatically generate the following routes:
+-----------+------------------------+-------------------------------------------------+---------------------------------+------------------------------------------------------------------+------------------------+ | Method | URI | Name | Action | Middleware | In | +-----------+------------------------+-------------------------------------------------+---------------------------------+------------------------------------------------------------------+------------------------+ | GET|HEAD | oauth/authorize | passport.authorizations.authorize | LaravelPassportHttpControllersAuthorizationController@show | web,auth | LaravelPassportHttpMiddlewareCheckClientCredentials,can:view-authorizations | | POST | oauth/authorize | passport.authorizations.approve | LaravelPassportHttpControllersApproveAuthorizationController | web,auth | LaravelPassportHttpMiddlewareCheckClientCredentials,can:approve-authorizations | | DELETE | oauth/authorize | passport.authorizations.deny | LaravelPassportHttpControllersDenyAuthorizationController | web,auth | LaravelPassportHttpMiddlewareCheckClientCredentials,can:deny-authorizations | | POST | oauth/clients | passport.clients.store | LaravelPassportHttpControllersClientController@store | web,auth | LaravelPassportHttpMiddlewareCheckClientCredentials,can:create-clients | | GET|HEAD | oauth/clients | passport.clients.index | LaravelPassportHttpControllersClientController@forUser | web,auth | LaravelPassportHttpMiddlewareCheckClientCredentials,can:view-clients | | PUT | oauth/clients/{client} | passport.clients.update | LaravelPassportHttpControllersClientController@update | web,auth | LaravelPassportHttpMiddlewareCheckClientCredentials,can:update-clients | | DELETE | oauth/clients/{client} | passport.clients.destroy | LaravelPassportHttpControllersClientController@destroy | web,auth | LaravelPassportHttpMiddlewareCheckClientCredentials,can:delete-clients | | POST | oauth/token | passport.token | LaravelPassportHttpControllersAccessTokenController@issueToken| throttle | LaravelPassportHttpMiddlewareCheckClientCredentials,can:issue-tokens | | POST | oauth/token/refresh | passport.token.refresh | LaravelPassportHttpControllersTransientTokenController@refresh | throttle | LaravelPassportHttpMiddlewareCheckClientCredentials,can:refresh-tokens | | DELETE | oauth/tokens/{token} | passport.tokens.destroy | LaravelPassportHttpControllersAuthorizedAccessTokenController@destroy | web,auth | LaravelPassportHttpMiddlewareCheckClientCredentials,throttle:60,1,oauth | | GET|HEAD | oauth/tokens | passport.tokens.index | LaravelPassportHttpControllersAuthorizedAccessTokenController@forUser | web,auth | LaravelPassportHttpMiddlewareCheckClientCredentials,can:view-tokens | | DELETE | oauth/tokens | passport.tokens.destroy.all | LaravelPassportHttpControllersAuthorizedAccessTokenController@destroyAll| web,auth | LaravelPassportHttpMiddlewareCheckClientCredentials,can:delete-tokens | +-----------+------------------------+-------------------------------------------------+---------------------------------+------------------------------------------------------------------+------------------------+
These routes are Passport built-in routes and use the passport.
prefix name.
Now we are ready to start defining the OAuth2 client. We can use the previously generated API key to create an OAuth2 client.
Create a new OAuth2 client in the database. We can create it manually or use the artisan command passport:client
provided by Laravel Passport to create it.
During the creation process, we need to specify the client's name, key, callback URL, etc.
Create manually:
INSERT INTO `oauth_clients` (`id`, `user_id`, `name`, `secret`, `redirect`, `revoked`, `personal_access_client`, `password_client`, `updated_at`, `created_at`) VALUES (1, NULL, 'My Client', 'my-client-secret', 'http://localhost/callback', 0, 0, 1, '2021-10-01 00:00:00', '2021-10-01 00:00:00');
Create with artisan:
php artisan passport:client --client --name="My Client"
After running this command, it will automatically generate the OAuth2 client and display the client ID and secret.
Now that we have the OAuth2 client ready and the OAuth2 routes defined, we can start using the OAuth2 protocol to generate access tokens.
We can generate an access token using the passport:client
command:
php artisan passport:client --client --password
After running this command, it will generate an OAuth2 client and automatically generate for that client An access token.
The final step is to use the OAuth2 access token to make the API call. We can use Laravel's own Guzzle
to send HTTP requests and send the access token as the Authorization Header.
use GuzzleHttpClient; $client = new Client(); $response = $client->request('GET', 'http://localhost/api/user', [ 'headers' => [ 'Authorization' => 'Bearer '.$accessToken, ], ]); $body = $response->getBody()->getContents();
It should be noted that for each request, we need to send a valid access token. This can be achieved by using the Passport::actingAs
method, which replaces the specified user ID with a valid authorization token.
use LaravelPassportPassport; Passport::actingAs($user); $response = $client->request('GET', 'http://localhost/api/user', [ 'headers' => [ 'Authorization' => 'Bearer '.$accessToken, ], ]);
In this article, we introduced how to use Laravel Passport to manage the OAuth2 protocol. Laravel Passport makes it easy to generate API keys, configure OAuth2 services, create OAuth2 routes, define OAuth2 clients, generate OAuth2 access tokens, and use them to make API calls. Laravel Passport is a very good choice when developing web applications using the OAuth2 protocol.
The above is the detailed content of Laravel development: How to manage OAuth2 with Laravel Passport?. For more information, please follow other related articles on the PHP Chinese website!