Home  >  Article  >  PHP Framework  >  An article introducing the implementation mechanism of Token in Laravel

An article introducing the implementation mechanism of Token in Laravel

PHPz
PHPzOriginal
2023-04-23 09:13:141671browse

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