Table of Contents
Install Laravel Passport
Set Passport
Enable Passport
Enable automatic token refresh
Using Passport in the User model
Creating an OAuth2 client
Create API Route
Send HTTP request for authentication
Summary
Home PHP Framework Laravel Laravel development: How to implement APIOAuth2 authentication using Laravel Passport?

Laravel development: How to implement APIOAuth2 authentication using Laravel Passport?

Jun 15, 2023 am 10:28 AM
laravel oauth passport

Laravel is a very popular PHP framework. It is easy to use, highly scalable, and has high code readability. Laravel also provides many add-on packages (Packages) to implement various functions, including Laravel Passport, which is an API package for implementing OAuth2 authentication.

OAuth2 is a popular authorization framework that simplifies the authorization process and is widely used in web and mobile applications. In order to use OAuth2, we need to implement an authorization server to generate tokens and allow clients to use the API. Laravel Passport provides us with an easy way to implement OAuth2 authentication.

This article will introduce how to use Laravel Passport to implement OAuth2 authentication. Before starting, it is assumed that the Laravel framework is already installed.

Install Laravel Passport

You can use Composer to install Laravel Passport. Run the following command in the root directory of your Laravel application:

composer require laravel/passport
Copy after login

After the installation is complete, you need to run the following command to create the necessary tables for Laravel Passport:

php artisan migrate
Copy after login

Next run the following command to create the necessary tables for Laravel Passport generates an encryption key:

php artisan passport:install
Copy after login

The generated key will be used to encrypt the generated token.

Set Passport

After completing the installation, you need to configure Laravel Passport in your application. The following are the necessary steps:

Enable Passport

To enable Laravel Passport, you first need to call the Passport::routes() method. This method will register the necessary routes:

//在bootstrap/app.php文件中加入下面这行代码
LaravelPassportPassport::routes();
Copy after login

Enable automatic token refresh

By default, the token will automatically expire after it expires. If you want to automatically refresh tokens after they expire, you can use Passport::refreshTokensExpireIn() method in AuthServiceProvider. We add the following code snippet to the AuthServiceProvider:

//在AppProvidersAuthServiceProvider.php文件中加入下面这段代码
use LaravelPassportPassport;

//其他代码...

public function boot()
{
    $this->registerPolicies();

    Passport::routes();

    Passport::tokensExpireIn(Carbon::now()->addDays(15));

    Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
}
Copy after login

In this example, the tokensExpireIn() method sets the token expiration time to 15 days, and the refreshTokensExpireIn()Method sets the expiration time of the automatically refreshed token to 30 days.

Using Passport in the User model

Now you need to enable the Laravel Passport feature in the User model. This can be achieved by using the Passport::use() method on the User class:

//在app/User.php文件中加入下面这段代码
use LaravelPassportHasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
}
Copy after login

Creating an OAuth2 client

When using OAuth2 authentication in an application, it needs to be generated by an authorization server API token. In order to communicate with the authorization server, a client needs to be created. You can create a client by running the passport:client command:

php artisan passport:client --password
Copy after login

After running this command, you will be prompted to enter the application name. If you do not want to enter a name, you can choose to use the default value and return Just take a car.

After the operation is completed, a client_id and client_secret will be generated. client_id and client_secret will be used to communicate with the authorization server.

Create API Route

After creating the OAuth2 client, you need to create an API route so that the authorization server can access the API.

//在routes/api.php文件中加入以下代码
Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});
Copy after login

In this example, OAuth2 authentication is required for the route specified by using the auth:api middleware. If a valid API token is not provided, this route will return a 401 Unauthorized HTTP response.

Send HTTP request for authentication

You are now ready to send a request to the API and authenticate using OAuth2 credentials.

You can use tools such as Postman to test the API, and the request needs to contain a valid API token. In Postman, it is possible to include an Authorization header in the request, for example:

Authorization: Bearer [access_token]
Copy after login

access_token must be replaced with the previously generated token.

Summary

Laravel Passport is an easy-to-use OAuth2 server that makes it easy to implement API authentication without having to write a lot of code. In this article, we covered the steps on how to implement OAuth2 authentication using Laravel Passport and showed how to create an OAuth2 client and API routes and authenticate via HTTP requests. If your application needs to use API authentication, then Laravel Passport may be one of the ideal choices for you.

The above is the detailed content of Laravel development: How to implement APIOAuth2 authentication using 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

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

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

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

Laravel - Pagination Customizations Laravel - Pagination Customizations Aug 27, 2024 am 10:51 AM

Laravel - Pagination Customizations - Laravel includes a feature of pagination which helps a user or a developer to include a pagination feature. Laravel paginator is integrated with the query builder and Eloquent ORM. The paginate method automatical

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

Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Laravel schedule task is not executed: What should I do if the task is not running after schedule: run command? Mar 31, 2025 pm 11:24 PM

Laravel schedule task run unresponsive troubleshooting When using Laravel's schedule task scheduling, many developers will encounter this problem: schedule:run...

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 - Dump Server Laravel - Dump Server Aug 27, 2024 am 10:51 AM

Laravel - Dump Server - Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file.

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

See all articles