Using JWT validation in ThinkPHP6
With the development of the Internet, the number of users of Web applications has gradually increased, and security issues have become increasingly important. Authentication is an important part of web application security because only authenticated users can access resources that require permissions.
JSON Web Token (JWT) is a lightweight, self-contained authentication token that is a great way to securely transfer information between web applications. The JWT authentication scheme is suitable for distributed systems and single-page applications.
ThinkPHP is a popular PHP framework that provides many tools to develop secure web applications. In this article, we will cover how to use JWT for authentication in ThinkPHP6 to enhance the security of your application.
Development environment and dependencies
Before we begin, we need to ensure that the development environment has been set up correctly. The following are the environments and dependencies used in this article. Please change accordingly based on your needs.
- PHP 7.2 or higher
- ThinkPHP 6.0.0 or higher
- Firebase JWT PHP library
Step 1 :Install the Firebase JWT PHP library
Installing the Firebase JWT PHP library is the first step in using the JWT authentication scheme. This library will help us create, sign and verify JWTs.
We can use Composer to install the Firebase JWT PHP library. Enter the following command at the command line:
composer require firebase/php-jwt
Step 2: Create the Token class
To facilitate the management and use of JWT, we create a class named Token to handle various aspects of JWT verification. This class will include functions such as creating tokens, verifying tokens, and obtaining token information.
Create the Token.php file in the app/common directory and add the following code:
<?php namespace appcommon; use FirebaseJWTJWT; class Token { private static $key = 'your_secret_key'; private static $alg = 'HS256'; public static function createToken($data, $expiration = 3600) { $payload = [ 'iss' => 'localhost', 'sub' => 'token', 'iat' => time(), 'exp' => time() + $expiration, 'data' => $data ]; return JWT::encode($payload, self::$key, self::$alg); } public static function decodeToken($token) { return JWT::decode($token, self::$key, [self::$alg]); } public static function getDataByToken($token) { $decoded = self::decodeToken($token); if (isset($decoded->data)) { return $decoded->data; } else { return false; } } public static function verifyToken($token) { $result = false; try { $decoded = self::decodeToken($token); $result = true; } catch (Exception $e) { // Invalid token } return $result; } }
In the code, we use encode in the
FirebaseJWTJWT library ()
and decode()
methods to create and parse JWT. $key
is the key we used to sign the JWT and $alg
is the algorithm we chose. In the createToken()
method, we use the four keys (iss, iat, exp and sub) from the JWT payload and add custom data
. $expiration
The parameter specifies the expiration time of the JWT. Therefore, JWT can only be used within the validity period.
Step 3: Validate the token in the middleware
Now that we have created the Token class to handle the JWT related work, we need to validate the user JWT in the middleware. Using middleware makes it easy to intercept and set responses in your application's controller code, and you can separate the code into different classes for better management and modification.
Create the Jwt.php file in the app/middleware directory and add the following code:
<?php namespace appmiddleware; use appcommonToken; use thinkexceptionHttpResponseException; use thinkResponse; class Jwt { public function handle($request, Closure $next) { if (!$request->header('Authorization')) { return json(['code' => 401, 'msg' => 'Unauthorized']); } $header = $request->header('Authorization'); $token = substr($header, 7); if (Token::verifyToken($token)) { $request->data = Token::getDataByToken($token); return $next($request); } else { return json(['code' => 401, 'msg' => 'Unauthorized']); } } }
In this middleware, we use verifyToken()## in the Token class #Method to verify JWT. This method will return true or false indicating whether the token is valid. If valid, we will use the
getDataByToken() method to get the data portion of the JWT and store it in
$request->data. This data is then available to the controller.
/api/user, we need to set the route in the
route pi.php file as follows:
use appmiddlewareJwt; Route::group('api', function() { Route::get('user', 'UserController@getUserInfo')->middleware(Jwt::class); });Please note that in this route, we pass the
Jwt middleware as a parameter to the
middleware() method. This is the sample code for the
getUserInfo() method in
UserController.
<?php namespace appcontroller; use appcommonToken; class UserController { public function getUserInfo() { $data = request()->data; ... } ... }In the controller, you can access the data stored in the authenticated JWT by calling
$request->data.
The above is the detailed content of Using JWT validation in ThinkPHP6. 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)

The settings.json file is located in the user-level or workspace-level path and is used to customize VSCode settings. 1. User-level path: Windows is C:\Users\\AppData\Roaming\Code\User\settings.json, macOS is /Users//Library/ApplicationSupport/Code/User/settings.json, Linux is /home//.config/Code/User/settings.json; 2. Workspace-level path: .vscode/settings in the project root directory

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

@property decorator is used to convert methods into properties to implement the reading, setting and deletion control of properties. 1. Basic usage: define read-only attributes through @property, such as area calculated based on radius and accessed directly; 2. Advanced usage: use @name.setter and @name.deleter to implement attribute assignment verification and deletion operations; 3. Practical application: perform data verification in setters, such as BankAccount to ensure that the balance is not negative; 4. Naming specification: internal variables are prefixed, property method names are consistent with attributes, and unified access control is used to improve code security and maintainability.

itertools.combinations is used to generate all non-repetitive combinations (order irrelevant) that selects a specified number of elements from the iterable object. Its usage includes: 1. Select 2 element combinations from the list, such as ('A','B'), ('A','C'), etc., to avoid repeated order; 2. Take 3 character combinations of strings, such as "abc" and "abd", which are suitable for subsequence generation; 3. Find the combinations where the sum of two numbers is equal to the target value, such as 1 5=6, simplify the double loop logic; the difference between combinations and arrangement lies in whether the order is important, combinations regard AB and BA as the same, while permutations are regarded as different;

Python is an efficient tool to implement ETL processes. 1. Data extraction: Data can be extracted from databases, APIs, files and other sources through pandas, sqlalchemy, requests and other libraries; 2. Data conversion: Use pandas for cleaning, type conversion, association, aggregation and other operations to ensure data quality and optimize performance; 3. Data loading: Use pandas' to_sql method or cloud platform SDK to write data to the target system, pay attention to writing methods and batch processing; 4. Tool recommendations: Airflow, Dagster, Prefect are used for process scheduling and management, combining log alarms and virtual environments to improve stability and maintainability.

fixture is a function used to provide preset environment or data for tests. 1. Use the @pytest.fixture decorator to define fixture; 2. Inject fixture in parameter form in the test function; 3. Execute setup before yield, and then teardown; 4. Control scope through scope parameters, such as function, module, etc.; 5. Place the shared fixture in conftest.py to achieve cross-file sharing, thereby improving the maintainability and reusability of tests.

Use the uuid module to obtain the MAC address of the first network card of the machine across the platform, without the need for a third-party library, and convert it into a standard format through uuid.getnode(); 2. Use subprocess to call system commands such as ipconfig or ifconfig, and combine it with regular extraction of all network card MAC addresses, which is suitable for scenarios where multiple network card information needs to be obtained; 3. Use the third-party library getmac, call get_mac_address() after installation to obtain the MAC, which supports query by interface or IP, but requires additional dependencies; in summary, if no external library is needed, the uuid method is recommended. If you need to flexibly obtain multi-network card information, you can use the subprocess solution to allow you to install the dependency getma.
