search
HomePHP FrameworkLaravelLaravel development: How to implement API authentication using Laravel Passport and JWT?

Laravel Development: How to implement API authentication using Laravel Passport and JWT?

API (Application Programming Interface) authentication is a common requirement in today's Internet applications. As a popular PHP framework, Laravel provides two tools, Laravel Passport and JWT (JSON Web Tokens), which can help us implement API authentication.

This article will introduce how to use Laravel Passport and JWT to implement API authentication. In the following content, we will understand the basic concepts of these two tools and how to configure and use them in Laravel applications.

What is Laravel Passport?

Laravel Passport is an OAuth2 server specially developed for the Laravel framework, which can help us build API authentication systems quickly and securely. Passport provides a set of APIs to perform the authentication process, and has internally implemented a series of authentication methods specified by the OAuth2 protocol.

Among them, OAuth2 is a standard protocol that uses proxy authorization. Proxy authorization is an authorization mechanism for obtaining access to resources on behalf of a user. The OAuth2 protocol issues "access tokens" to third-party applications to access protected resources on behalf of the user. Therefore, Passport actually plays the role of OAuth2 authentication server in Laravel applications.

What is JWT?

JWT (JSON Web Tokens) is an open standard (RFC 7519) for authentication and authorization in distributed network environments. JWT is commonly used to pass authenticated user identity information and claims between clients and servers. JWT consists of three parts: header, payload and signature.

Usually, the header contains the type of JWT and the encryption algorithm used, the payload contains user identity information and claims, and the signature is used to verify the authenticity of the JWT. When using JWT for authentication, the server determines the user's identity by decrypting the information in the JWT, thereby achieving API authentication.

Configuring Laravel Passport and JWT

Before using Laravel Passport and JWT for API authentication, we need to configure it in the Laravel application first. The following are the specific configuration steps:

Step 1: Install Laravel Passport and tymon/jwt-auth

Use composer to install Laravel Passport and tymon/jwt-auth in the command line tool:

composer require laravel/passport
composer require tymon/jwt-auth

Step 2: Configure Laravel Passport

In the config/app.php file, add the following service provider:

'providers' => [
    ...
    LaravelPassportPassportServiceProvider::class,
],

Then, run the following command to create the Passport data table:

php artisan migrate

For Passport’s default authentication method “Password Grant”, we add “PassportHasApiTokens” (Passport’s default user authentication Trait) to the User model. Open the User.php file and add the following content:

use LaravelPassportHasApiTokens;

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;
    ...
}

Step 3: Configure JWT

First, in the config/app.php file, add JWTServiceProvider:

'providers' => [
    ...
    TymonJWTAuthProvidersLaravelServiceProvider::class,
],

Then , run the following command to generate the secret key required for JWT:

php artisan jwt:secret

In the config/auth.php file, add the jwt guard configuration (use jwt as the guard guard option), and set the default authentication driver Set to "jwt":

'guards' => [
    ...
    'jwt' => [
        'driver' => 'jwt',
        'provider' => 'users'
    ],
],
...
'defaults' => [
    'guard' => 'jwt',
    ...
],

In the config/auth.php file, add the JWT user provider users configuration (instructing to use the Eloquent model):

'providers' => [
    ...
    'users' => [
        'driver' => 'eloquent',
        'model' => AppModelsUser::class
    ]
],

Use Laravel Passport and JWT API Authentication

After the preparation work is completed, we can happily implement API authentication using Laravel Passport and JWT. The following is the specific operation process:

Step 1: Register API routing

First, register the API routing in the routes/api.php file. For example, we define a GET route for obtaining user information:

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Laravel's middleware auth:api is used here, which will ensure that requests from authenticated users can pass. With routing middleware, we add this step of authentication to the route.

Step 2: Create an access token

Users need an access token to access the API. We need to use password authorization access token. The specific implementation steps are as follows:

You need to first define a route to receive the user name and password provided by the user:

Route::post('/login', function (Request $request) {
    $http = new GuzzleHttpClient;

    $response = $http->post('http://your-app.com/oauth/token', [
        'form_params' => [
            'grant_type' => 'password',
            'client_id' => 'client-id',
            'client_secret' => 'client-secret',
            'username' => $request->username,
            'password' => $request->password,
            'scope' => '',
        ],
    ]);

    return json_decode((string) $response->getBody(), true);
});

In the above code, we use GuzzleHttp The client sends a POST request to obtain the access token. Among them, grant_type must be "password", client_id and client_secret respectively correspond to the ID and Secret applied in Laravel Passport. After the request is successful, a JSON response will be returned containing the user's access token access_token to access the API.

Step 3: Initiate API request

We can use the obtained token access_token to send a request to the API, verify the user's identity, and obtain protected resources. When making a request to the API, you must add the Authorization key-value pair in the header, whose value is "Bearer access_token". For example:

$accessToken = 'your-access-token';
$response = $http->withHeaders([
    'Authorization' => 'Bearer ' . $accessToken
])->get('http://your-app.com/api/user');

If the request is successful, the API will return user information.

Conclusion

In Laravel applications, Laravel Passport provides a powerful OAuth2 authentication protocol and API authentication function, and JWT is a safe and convenient authentication method. In actual development, we can use Laravel Passport and JWT in combination to improve the security and reliability of the API and protect user data from being stolen or tampered with by malicious attackers.

The above is the detailed content of Laravel development: How to implement API authentication using Laravel Passport and JWT?. 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
一起来聊聊Laravel的生命周期一起来聊聊Laravel的生命周期Apr 25, 2022 pm 12:04 PM

本篇文章给大家带来了关于laravel的相关知识,其中主要介绍了关于Laravel的生命周期相关问题,Laravel 的生命周期从public\index.php开始,从public\index.php结束,希望对大家有帮助。

如何使用ThinkPHP6进行JWT认证?如何使用ThinkPHP6进行JWT认证?Jun 12, 2023 pm 12:18 PM

JWT(JSONWebToken)是一种轻量级的认证和授权机制,它使用JSON对象作为安全令牌,可以在多个系统之间安全地传输用户身份信息。而ThinkPHP6是一种基于PHP语言的高效、灵活的MVC框架,它提供了许多有用的工具和功能,其中就包括JWT认证机制。在本文中,我们将介绍如何使用ThinkPHP6进行JWT认证,以保障Web应用程序的安全性和可靠

如何在PHP中使用JWT和JWE进行API身份验证和加密如何在PHP中使用JWT和JWE进行API身份验证和加密Jun 17, 2023 pm 02:42 PM

随着互联网的发展,越来越多的网站和应用需要提供API接口来进行数据交互。在这种情况下,API身份验证和加密成为了非常重要的问题。而JWT和JWE作为一种流行的身份验证和加密机制,在PHP中的应用也越来越广泛。那么,本文将介绍如何在PHP中使用JWT和JWE进行API身份验证和加密。JWT的基本概念JWT代表JSONWe

PHP中的安全JWT令牌生成与验证技术解析PHP中的安全JWT令牌生成与验证技术解析Jul 01, 2023 pm 06:06 PM

PHP中的安全JWT令牌生成与验证技术解析随着网络应用的发展,用户身份验证和授权变得越来越重要。JsonWebToken(JWT)是一种用于在网络应用中安全传输信息的开放标准(RFC7519)。在PHP开发中,使用JWT令牌来实现用户身份验证和授权已成为一种常见的做法。本文将介绍PHP中的安全JWT令牌生成与验证技术。一、JWT基础知识在了解如何生成与

PHP中的OAuth:创建一个JWT授权服务器PHP中的OAuth:创建一个JWT授权服务器Jul 28, 2023 pm 05:27 PM

PHP中的OAuth:创建一个JWT授权服务器随着移动应用和前后端分离的趋势的兴起,OAuth成为了现代Web应用中不可或缺的一部分。OAuth是一种授权协议,通过提供标准化的流程和机制,用于保护用户的资源免受未经授权的访问。在本文中,我们将学习如何使用PHP创建一个基于JWT(JSONWebTokens)的OAuth授权服务器。JWT是一种用于在网络中

Vue.js实现登录验证的完整指南(API、JWT、axios)Vue.js实现登录验证的完整指南(API、JWT、axios)Jun 09, 2023 pm 04:04 PM

Vue.js是一种流行的JavaScript框架,用于构建动态Web应用程序。实现用户登录验证是开发Web应用程序的必要部分之一。本文将介绍使用Vue.js、API、JWT和axios实现登录验证的完整指南。创建Vue.js应用程序首先,我们需要创建一个新的Vue.js应用程序。我们可以使用VueCLI或手动创建一个Vue.js应用程序。安装axiosax

深入解析JWT(JSON Web Token)的原理及用法深入解析JWT(JSON Web Token)的原理及用法Jan 10, 2023 am 10:55 AM

本篇文章给大家带来了关于JWT的相关知识,其中主要介绍了什么是JWT?JWT的原理以及用法是什么?感兴趣的朋友,下面一起来看一下吧,希望对大家有帮助。

如何使用JWT在PHP应用中实现身份验证和授权如何使用JWT在PHP应用中实现身份验证和授权Aug 03, 2023 pm 10:17 PM

如何使用JWT在PHP应用中实现身份验证和授权引言:随着互联网的快速发展,身份验证和授权在Web应用程序中变得日益重要。JSONWebToken(JWT)是一种流行的认证和授权机制,它在PHP应用中广泛应用。本文将介绍如何使用JWT在PHP应用中实现身份验证和授权,并提供代码示例,帮助读者更好地理解JWT的使用方法。一、JWT简介JSONWebTo

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft