Table of Contents
Generate API key using Laravel Passport
Configure OAuth2 service
Create OAuth2 routes
Define OAuth2 client
Generate OAuth2 Access Token
Using the OAuth2 access token to make the API call
Conclusion
Home PHP Framework Laravel Laravel development: How to manage OAuth2 with Laravel Passport?

Laravel development: How to manage OAuth2 with Laravel Passport?

Jun 13, 2023 pm 05:14 PM
laravel oauth passport

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.

Generate API key using Laravel Passport

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
Copy after login

Then, run the migration command:

php artisan migrate
Copy after login

Next, use Passport’s client:secret command Generate API Key:

php artisan passport:client --password
Copy after login

This will generate a client ID and a client secret.

Configure OAuth2 service

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,
    ],
],
Copy after login

Create OAuth2 routes

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
Copy after login

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                                      |
+-----------+------------------------+-------------------------------------------------+---------------------------------+------------------------------------------------------------------+------------------------+
Copy after login

These routes are Passport built-in routes and use the passport. prefix name.

Define OAuth2 client

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');
Copy after login

Create with artisan:

php artisan passport:client --client --name="My Client"
Copy after login

After running this command, it will automatically generate the OAuth2 client and display the client ID and secret.

Generate OAuth2 Access Token

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
Copy after login

After running this command, it will generate an OAuth2 client and automatically generate for that client An access token.

Using the OAuth2 access token to make the API call

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();
Copy after login

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,
    ],
]);
Copy after login

Conclusion

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP vs. Flutter: The best choice for mobile development PHP vs. Flutter: The best choice for mobile development May 06, 2024 pm 10:45 PM

PHP vs. Flutter: The best choice for mobile development

Laravel - Artisan Commands Laravel - Artisan Commands Aug 27, 2024 am 10:51 AM

Laravel - Artisan Commands

Analysis of the advantages and disadvantages of PHP unit testing tools Analysis of the advantages and disadvantages of PHP unit testing tools May 06, 2024 pm 10:51 PM

Analysis of the advantages and disadvantages of PHP unit testing tools

How to use object-relational mapping (ORM) in PHP to simplify database operations? How to use object-relational mapping (ORM) in PHP to simplify database operations? May 07, 2024 am 08:39 AM

How to use object-relational mapping (ORM) in PHP to simplify database operations?

PHP distributed system architecture and practice PHP distributed system architecture and practice May 04, 2024 am 10:33 AM

PHP distributed system architecture and practice

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

Comparison of the latest versions of Laravel and CodeIgniter

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

How do the data processing capabilities in Laravel and CodeIgniter compare?

PHP code unit testing and integration testing PHP code unit testing and integration testing May 07, 2024 am 08:00 AM

PHP code unit testing and integration testing

See all articles