An article introducing the implementation mechanism of Token in Laravel
Apr 23, 2023 am 09:13 AMLaravel 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:
- You can start using it without configuration;
- Supports multiple authentication methods such as session, Token and API key;
- Built-in multiple authentication implementations, such as cookie, Token, auth, etc.;
- Provides convenient authentication and Token generation;
- 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:
- Create Token: When a user logs in, Sanctum will generate a random Token for the user and save the Token in the background database;
- Send Token: Send Token to the server as a request parameter or the Authorization field in the Header;
- Token verification: On the server side, Sanctum will check whether the received Token is valid and decide to authorize or reject;
- 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;? //?創(chuàng)建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!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

In Laravel, routing is the entry point of the application that defines the response logic when a client requests a specific URI. The route maps the URL to the corresponding processing code, which usually contains HTTP methods, URIs, and actions (closures or controller methods). 1. Basic structure of route definition: bind requests using Route::verb('/uri',action); 2. Supports multiple HTTP verbs such as GET, POST, PUT, etc.; 3. Dynamic parameters can be defined through {param} and data can be passed; 4. Routes can be named to generate URLs or redirects; 5. Use grouping functions to uniformly add prefixes, middleware and other sharing settings; 6. Routing files are divided into web.php, ap according to their purpose

InLaravel,policiesorganizeauthorizationlogicformodelactions.1.Policiesareclasseswithmethodslikeview,create,update,anddeletethatreturntrueorfalsebasedonuserpermissions.2.Toregisterapolicy,mapthemodeltoitspolicyinthe$policiesarrayofAuthServiceProvider.

To create new records in the database using Eloquent, there are four main methods: 1. Use the create method to quickly create records by passing in the attribute array, such as User::create(['name'=>'JohnDoe','email'=>'john@example.com']); 2. Use the save method to manually instantiate the model and assign values ??to save one by one, which is suitable for scenarios where conditional assignment or extra logic is required; 3. Use firstOrCreate to find or create records based on search conditions to avoid duplicate data; 4. Use updateOrCreate to find records and update, if not, create them, which is suitable for processing imported data, etc., which may be repetitive.

Thephpartisandb:seedcommandinLaravelisusedtopopulatethedatabasewithtestordefaultdata.1.Itexecutestherun()methodinseederclasseslocatedin/database/seeders.2.Developerscanrunallseeders,aspecificseederusing--class,ortruncatetablesbeforeseedingwith--trunc

Artisan is a command line tool of Laravel to improve development efficiency. Its core functions include: 1. Generate code structures, such as controllers, models, etc., and automatically create files through make: controller and other commands; 2. Manage database migration and fill, use migrate to run migration, and db:seed to fill data; 3. Support custom commands, such as make:command creation command class to implement business logic encapsulation; 4. Provide debugging and environment management functions, such as key:generate to generate keys, and serve to start the development server. Proficiency in using Artisan can significantly improve Laravel development efficiency.

Yes,youcaninstallLaravelonanyoperatingsystembyfollowingthesesteps:1.InstallPHPandrequiredextensionslikembstring,openssl,andxmlusingtoolslikeXAMPPonWindows,HomebrewonmacOS,oraptonLinux;2.InstallComposer,usinganinstalleronWindowsorterminalcommandsonmac

ToruntestsinLaraveleffectively,usethephpartisantestcommandwhichsimplifiesPHPUnitusage.1.Setupa.env.testingfileandconfigurephpunit.xmltouseatestdatabaselikeSQLite.2.Generatetestfilesusingphpartisanmake:test,using--unitforunittests.3.Writetestswithmeth

Defining a method (also known as an action) in a controller is to tell the application what to do when someone visits a specific URL. These methods usually process requests, process data, and return responses such as HTML pages or JSON. Understanding the basic structure: Most web frameworks (such as RubyonRails, Laravel, or SpringMVC) use controllers to group related operations. Methods within each controller usually correspond to a route, i.e. the URL path that someone can access. For example, there may be the following methods in PostsController: 1.index() – display post list; 2.show() – display individual posts; 3.create() – handle creating new posts; 4.u
