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 AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

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)

How to get the return code when email sending fails in Laravel? How to get the return code when email sending fails in Laravel? Apr 01, 2025 pm 02:45 PM

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

In Laravel, how to deal with the situation where verification codes are failed to be sent by email? In Laravel, how to deal with the situation where verification codes are failed to be sent by email? Mar 31, 2025 pm 11:48 PM

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the custom table function of clicking to add data in dcat admin? How to implement the custom table function of clicking to add data in dcat admin? Apr 01, 2025 am 07:09 AM

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

Laravel Redis connection sharing: Why does the select method affect other connections? Laravel Redis connection sharing: Why does the select method affect other connections? Apr 01, 2025 am 07:45 AM

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Laravel multi-tenant extension stancl/tenancy: How to customize the host address of a tenant database connection? Apr 01, 2025 am 09:09 AM

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

Laravel Eloquent ORM in Bangla partial model search) Laravel Eloquent ORM in Bangla partial model search) Apr 08, 2025 pm 02:06 PM

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to effectively check the validity of Redis connections in Laravel6 project? How to effectively check the validity of Redis connections in Laravel6 project? Apr 01, 2025 pm 02:00 PM

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Laravel database migration encounters duplicate class definition: How to resolve duplicate generation of migration files and class name conflicts? Apr 01, 2025 pm 12:21 PM

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...

See all articles