search
HomePHP FrameworkLaravelAn article introducing the implementation mechanism of Token in Laravel

Laravel is a Web application framework developed using the PHP programming language. Its excellent performance is due to its internal integration of a large number of powerful extension packages. This includes the underlying implementation of Token. Token is a commonly used authentication method in web applications and is usually used to protect APIs and web services from illegal access. In this article, we will introduce the implementation mechanism of Token in Laravel.

1. The concept of token

Token, as the name suggests, refers to a token, a mark that can represent some kind of identity information or authorization information. It is usually generated by the server and issued to the client. After the client receives the token, it is stored locally and added to the request header or request parameters in subsequent requests as an identification of authentication or authorization. The server can determine whether the request has authentication or authorization information by checking whether the token is valid.

The use of tokens can more effectively protect web applications from unauthorized access, especially in APIs and web services, tokens are essential.

2. Implementation of Laravel Token

As an excellent web application framework, Laravel provides Token support in its built-in Auth function. In Laravel, Token is implemented using the Laravel Sanctum extension package.

2.1 Laravel Sanctum

Laravel Sanctum is a lightweight authentication package that can provide API authentication for Laravel applications, based on API keys or Tokens, making applications better Run in a stateless environment, such as SPA applications, single page applications and mobile applications. Laravel Sanctum provides the following functions:

  1. You can start using it without configuration;
  2. Supports multiple authentication methods such as session, Token and API key;
  3. Built-in multiple authentication implementations, such as cookie, Token, auth, etc.;
  4. Provides convenient authentication and Token generation;
  5. Better custom authentication process.

2.2 Token implementation principle

In Laravel Sanctum, the Token implementation principle is similar to the session implementation principle. In the request, when the client makes a request to the server, the Token is sent to the server as a request parameter or the Authorization field in the header. The server checks whether the Token is valid, and within the validity period, grants permission for the requested operation or returns an error message. The implementation process of Token is as follows:

  1. Create Token: When a user logs in, Sanctum will generate a random Token for the user and save the Token in the background database;
  2. Send Token: Send Token to the server as a request parameter or the Authorization field in the Header;
  3. Token verification: On the server side, Sanctum will check whether the received Token is valid and decide to authorize or reject;
  4. Tokens management: Sanctum provides a series of APIs to create, revoke, find and verify Tokens.

3. Use of Laravel Token

Sanctum provides a convenient and easy-to-use API to use Token, including Token creation, revocation, search and verification, etc. The following is how Token is used:

3.1 Install Sanctum

In the application, you first need to introduce Sanctum's dependency package into the application's composer.json file:

composer require laravel/sanctum

After the installation is complete, you need to add the following configuration to the config/app.php file:

'providers' => [ 
    // Other service providers... 
    Laravel\Sanctum\SanctumServiceProvider::class, 
],

3.2 Publish the configuration

After the installation is complete, you need to run the following command to publish the Sanctum configuration file:

php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"

3.3 Configuring Middleware

When using Sanctum, you need to add middleware to the corresponding route. In Laravel, API authentication middleware has been built in and can be called directly.

3.4 Create Token

After logging in, you can use the following code to create a Token for the current user:

use Illuminate\Http\Request; 
use Illuminate\Support\Facades\Hash; 
use Illuminate\Validation\ValidationException; 
use App\Models\User; 
use Illuminate\Support\Facades\Auth; 
use Illuminate\Support\Facades\Route; 

// 创建Token 
Route::post('/api/token/create', function (Request $request) { 
    $request->validate([ 
        'email' => 'required|email', 
        'password' => 'required', 
    ]); 

    $user = User::where('email', $request->email)->first(); 

    if (! $user || ! Hash::check($request->password, $user->password)) { 
        throw ValidationException::withMessages([ 
            'email' => ['The provided credentials are incorrect.'], 
        ]); 
    } 

    return $user->createToken($request->header('User-Agent'))->plainTextToken; 
});

In the above code, you can see that when creating a Token , using the machine's User-Agent as an additional parameter. The User-Agent here is an HTTP header that records browser or application-related information. This information will be used as part of the Token, so that once the Token is stolen or used maliciously, it can be easily discovered and revoked.

3.5 Revoke Token

Once the created Token is stolen or invalid, it can be revoked using the following code:

Auth::user()->tokens()->delete();

3.6 Verification extension

Sanctum also provides A good verification extension can easily perform access control. The code is as follows:

use Illuminate\Http\Request; 
use Illuminate\Support\Facades\Hash; 
use Illuminate\Validation\ValidationException; 
use App\Models\User; 
use Illuminate\Support\Facades\Auth; 
use Illuminate\Support\Facades\Route; 
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable 
{
    use HasApiTokens, Notifiable;
}

After using the above code, we can use the can interface in the User model for access control. The code is as follows:

$request->user()->can('update', $post);

In the above code, can will determine whether the user has the right to perform update operations based on the current user's role, permissions, and policies. It should be noted that users need to implement their own access control logic correctly.

4. Summary

In this article, we introduced the underlying implementation mechanism of Token in Laravel, especially the way to use the Sanctum extension package. Sanctum provides a convenient and easy-to-use API that can be quickly integrated into applications and improve application security. The usage, creation, revocation and management of Token, as well as access control are all explained in detail.

In today's Internet world, with the widespread application of APIs and Web services, Token, as a method of authentication, will be more widely used in many applications. The Laravel framework provides a good Token implementation mechanism that can better protect web applications from illegal access.

The above is the detailed content of An article introducing the implementation mechanism of Token in Laravel. 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
What is the latest Laravel version?What is the latest Laravel version?May 09, 2025 am 12:09 AM

As of October 2023, Laravel's latest version is 10.x. 1.Laravel10.x supports PHP8.1, improving development efficiency. 2.Jetstream improves support for Livewire and Inertia.js, simplifies front-end development. 3.EloquentORM adds full-text search function to improve data processing performance. 4. Pay attention to dependency package compatibility when using it and apply cache optimization performance.

Laravel Migrations: A Beginner's Guide to Database ManagementLaravel Migrations: A Beginner's Guide to Database ManagementMay 09, 2025 am 12:07 AM

LaravelMigrationsstreamlinedatabasemanagementbyprovidingversioncontrolforyourdatabaseschema.1)Theyallowyoutodefineandsharethestructureofyourdatabase,makingiteasytomanagechangesovertime.2)Migrationscanbecreatedandrunusingsimplecommands,ensuringthateve

Laravel migration: Best coding guideLaravel migration: Best coding guideMay 09, 2025 am 12:03 AM

Laravel's migration system is a powerful tool for developers to design and manage databases. 1) Ensure that the migration file is named clearly and use verbs to describe the operation. 2) Consider data integrity and performance, such as adding unique constraints to fields. 3) Use transaction processing to ensure database consistency. 4) Create an index at the end of the migration to optimize performance. 5) Maintain the atomicity of migration, and each file contains only one logical operation. Through these practices, efficient and maintainable migration code can be written.

Latest Laravel Version: Stay Up-to-Date with the Newest FeaturesLatest Laravel Version: Stay Up-to-Date with the Newest FeaturesMay 09, 2025 am 12:03 AM

Laravel's latest version is 10.x, released in early 2023. This version brings enhanced EloquentORM functionality and a simplified routing system, improving development efficiency and performance, but it needs to be tested carefully during upgrades to prevent problems.

Mastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMastering Laravel Soft Deletes: Best Practices and Advanced TechniquesMay 08, 2025 am 12:25 AM

Laravelsoftdeletesallow"deletion"withoutremovingrecordsfromthedatabase.Toimplement:1)UsetheSoftDeletestraitinyourmodel.2)UsewithTrashed()toincludesoft-deletedrecordsinqueries.3)CreatecustomscopeslikeonlyTrashed()forstreamlinedcode.4)Impleme

Laravel Soft Deletes: Restoring and Permanently Deleting RecordsLaravel Soft Deletes: Restoring and Permanently Deleting RecordsMay 08, 2025 am 12:24 AM

In Laravel, restore the soft deleted records using the restore() method, and permanently delete the forceDelete() method. 1) Use withTrashed()->find()->restore() to restore a single record, and use onlyTrashed()->restore() to restore a single record. 2) Permanently delete a single record using withTrashed()->find()->forceDelete(), and multiple records use onlyTrashed()->forceDelete().

The Current Laravel Release: Download and Upgrade Today!The Current Laravel Release: Download and Upgrade Today!May 08, 2025 am 12:22 AM

You should download and upgrade to the latest Laravel version as it provides enhanced EloquentORM capabilities and new routing features, which can improve application efficiency and security. To upgrade, follow these steps: 1. Back up the current application, 2. Update the composer.json file to the latest version, 3. Run the update command. While some common problems may be encountered, such as discarded functions and package compatibility, these issues can be solved through reference documentation and community support.

Laravel: When should I update to the last version?Laravel: When should I update to the last version?May 08, 2025 am 12:18 AM

YoushouldupdatetothelatestLaravelversionwhenthebenefitsclearlyoutweighthecosts.1)Newfeaturesandimprovementscanenhanceyourapplication.2)Securityupdatesarecrucialifvulnerabilitiesareaddressed.3)Performancegainsmayjustifyanupdateifyourappstruggles.4)Ens

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

Video Face Swap

Video Face Swap

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)