Laravel development: How to manage OAuth2 with Laravel 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
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.
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, ], ],
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
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.
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');
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.
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
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();
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, ], ]);
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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...

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

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

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...

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,...

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 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...

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...
