search
HomePHP FrameworkLaravelLaravel 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!

Statement
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
Using Laravel: Streamlining Web Development with PHPUsing Laravel: Streamlining Web Development with PHPApr 19, 2025 am 12:18 AM

Laravel optimizes the web development process including: 1. Use the routing system to manage the URL structure; 2. Use the Blade template engine to simplify view development; 3. Handle time-consuming tasks through queues; 4. Use EloquentORM to simplify database operations; 5. Follow best practices to improve code quality and maintainability.

Laravel: An Introduction to the PHP Web FrameworkLaravel: An Introduction to the PHP Web FrameworkApr 19, 2025 am 12:15 AM

Laravel is a modern PHP framework that provides a powerful tool set, simplifies development processes and improves maintainability and scalability of code. 1) EloquentORM simplifies database operations; 2) Blade template engine makes front-end development intuitive; 3) Artisan command line tools improve development efficiency; 4) Performance optimization includes using EagerLoading, caching mechanism, following MVC architecture, queue processing and writing test cases.

Laravel: MVC Architecture and Best PracticesLaravel: MVC Architecture and Best PracticesApr 19, 2025 am 12:13 AM

Laravel's MVC architecture improves the structure and maintainability of the code through models, views, and controllers for separation of data logic, presentation and business processing. 1) The model processes data, 2) The view is responsible for display, 3) The controller processes user input and business logic. This architecture allows developers to focus on business logic and avoid falling into the quagmire of code.

Laravel: Key Features and Advantages ExplainedLaravel: Key Features and Advantages ExplainedApr 19, 2025 am 12:12 AM

Laravel is a PHP framework based on MVC architecture, with concise syntax, powerful command line tools, convenient data operation and flexible template engine. 1. Elegant syntax and easy-to-use API make development quick and easy to use. 2. Artisan command line tool simplifies code generation and database management. 3.EloquentORM makes data operation intuitive and simple. 4. The Blade template engine supports advanced view logic.

Building Backend with Laravel: A GuideBuilding Backend with Laravel: A GuideApr 19, 2025 am 12:02 AM

Laravel is suitable for building backend services because it provides elegant syntax, rich functionality and strong community support. 1) Laravel is based on the MVC architecture, simplifying the development process. 2) It contains EloquentORM, optimizes database operations. 3) Laravel's ecosystem provides tools such as Artisan, Blade and routing systems to improve development efficiency.

Laravel framework skills sharingLaravel framework skills sharingApr 18, 2025 pm 01:12 PM

In this era of continuous technological advancement, mastering advanced frameworks is crucial for modern programmers. This article will help you improve your development skills by sharing little-known techniques in the Laravel framework. Known for its elegant syntax and a wide range of features, this article will dig into its powerful features and provide practical tips and tricks to help you create efficient and maintainable web applications.

The difference between laravel and thinkphpThe difference between laravel and thinkphpApr 18, 2025 pm 01:09 PM

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.

Laravel user login function listLaravel user login function listApr 18, 2025 pm 01:06 PM

Building user login capabilities in Laravel is a crucial task and this article will provide a comprehensive overview covering every critical step from user registration to login verification. We will dive into the power of Laravel’s built-in verification capabilities and guide you through customizing and extending the login process to suit specific needs. By following these step-by-step instructions, you can create a secure and reliable login system that provides a seamless access experience for users of your Laravel application.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment