


Full record of the actual simulation process of JWT login authentication
Apr 03, 2024 pm 01:22 PMAfter careful compilation by php editor Banana, we introduce to you a popular full record of the actual development simulation process - JWT login authentication actual simulation. JWT (JSON Web Token) is an open standard for authentication. It generates a token (Token) after the user successfully logs in, and the user carries this token in subsequent requests for identity authentication. This article will provide an in-depth analysis of the implementation process of JWT login authentication and provide a comprehensive practical demonstration recording. In the process, we will take you to understand the principles of JWT and how to apply it in actual development. Whether you are a beginner or an experienced developer, you can gain valuable knowledge and practical experience from this article.
Token authentication process
- As the most popular cross-domain authentication solution, JWT (JSON WEB Token) is deeply lovedDevelopers's favorite, the main process is as follows:
- The client sends an account and password request to log in
- The server receives the request and verifies whether the account password is passed
- After successful verification, the server will generate a unique token and return it to the client.
- The client receives the token and stores it in cookie or localStroge.
- After that, every client When the client sends a request to the server, it will carry the token through a cookie or header
The server verifies the validity of the token and returns the response data only after passing the request
Token authentication advantages
- Supports cross-domain access: Cookies do not allow cross-domain access. This does not exist for the Token mechanism, provided that the user authentication information transmitted passesHttpHeader transmission
- Stateless: The Token mechanism does not need to store session information on the server side, because the Token itself contains the information of all logged-in users, and only needs to store state information in the client's cookie or local media
- Wider applicability: As long as the client supports the http protocol, token authentication can be used.
- No need to consider CSRF: Since it no longer relies on cookies, CSRF will not occur when using token authentication, so there is no need to consider CSRF defense
JWT structure
- A JWT is actually a string, which consists of three parts: header, payload and signature. Use a dot . in the middle to separate it into three parts. Note that there are no line breaks inside the JWT.
? Header/header
header
consists of two parts: The type of token
JWT
and algorithmname:H<strong class="keylink">Mac</strong>
,SHA256
,RSA
{ "alg": "HS256", "typ": "JWT" }
? Payload/Payload
##Payload part is also a
js<strong class="keylink">ON </strong> Object, used to store the actual data that needs to be transferred.
JWT Specifies seven default fields to choose from.
iss: Issuerexp: expiration time
sub: topic
aud: user
nbf: not available before
iat: publication time
jti: JWT ID used to identify this JWT
{ "iss": "xxxxxxx", "sub": "xxxxxxx", "aud": "xxxxxxx", "user": [ 'username': '极客飞兔', 'gender': 1, 'nickname': '飞兔小哥' ] }
- ?
- Signature/Signature The signature part is the data signature of the above two parts of the header and payload data
- In order to ensure that the data is not tampered with, you need to specify a key, which is generally known only to you and stored on the server. The code to generate the signature is generally as follows:
// 其中secret 是密钥 String signature = HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
- The client receives the JWT returned by the
- server, which can be stored in Cookie or localStorage Then every time the client communicates with the server, it must bring this JWTSave the JWT in the cookie to send the request, so that it cannot cross domainA better approach is to put it in the HTTP request In the Authorization field of the header information
fetch('license/login', { headers: { 'Authorization': 'X-TOKEN' + token } })
ThinkPHP<strong class="keylink">6</strong>Integration
JWT Login authentication for actual simulation
Install JWT extension
composer require firebase/php-jwt
Encapsulation to generate JWT and decryption method
<?php namespace app\services; use app\Helper; use Firebase\JWT\JWT; use Firebase\JWT\Key; class JwtService { protected $salt; public function __construct() { //从配置信息这种或取唯一字符串,你可以随便写比如md5('token') $this->salt = config('jwt.salt') || "autofelix"; } // jwt生成 public function generateToken($user) { $data = array( "iss" => 'autofelix',//签发者 可以为空 "aud" => 'autofelix', //面象的用户,可以为空 "iat" => Helper::getTimestamp(), //签发时间 "nbf" => Helper::getTimestamp(), //立马生效 "exp" => Helper::getTimestamp() + 7200, //token 过期时间 两小时 "user" => [ // 记录用户信息 'id' => $user->id, 'username' => $user->username, 'truename' => $user->truename, 'phone' => $user->phone, 'email' => $user->email, 'role_id' => $user->role_id ] ); $jwt = JWT::encode($data, md5($this->salt), 'HS256'); return $jwt; } // jwt解密 public function chekToken($token) { JWT::$leeway = 60; //当前时间减去60,把时间留点余地 $decoded = JWT::decode($token, new Key(md5($this->salt), 'HS256')); return $decoded; } }
After the user logs in, a JWT identification is generated
<?php declare (strict_types=1); namespace app\controller; use think\Request; use app\ResponseCode; use app\Helper; use app\model\User as UserModel; use app\services\JwtService; class License { public function login(Request $request) { $data = $request->only(['username', 'passWord', 'code']); // ....进行验证的相关逻辑... $user = UserModel::where('username', $data['username'])->find(); // 验证通过生成 JWT, 返回给前端保存 $token = (new JwtService())->generateToken($user); return json([ 'code' => ResponseCode::SUCCESS, 'message' => '登录成功', 'data' => [ 'token' => $token ] ]); } }
Middleware verifies whether the user is logged in
Registermiddleware in middleware.php
##
<?php // 全局中间件定义文件 return [ // ...其他中间件 // JWT验证 \app\middleware\Auth::class ];
<?php declare (strict_types=1); namespace app\middleware; use app\ResponseCode; use app\services\JwtService; class Auth { private $router_white_list = ['login']; public function handle($request, \Closure $next) { if (!in_array($request->pathinfo(), $this->router_white_list)) { $token = $request->header('token'); try { // jwt 验证 $jwt = (new JwtService())->chekToken($token); } catch (\Throwable $e) { return json([ 'code' => ResponseCode::ERROR, 'msg' => 'Token验证失败' ]); } $request->user = $jwt->user; } return $next($request); } }
附:为什么使用jwt而不使用session
- session是将客户端数据储存在服务器的内存,当客服端的数据过多,服务器的内存开销大;
- session的数据储存在某台服务器,在分布式的项目中无法做到共享;
- jwt的安全性更好。
总而言之,如果使用了分布式,切只能在session和jwt里面选的时候,就一定要选jwt。
The above is the detailed content of Full record of the actual simulation process of JWT login authentication. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

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



This article will explain in detail how PHP formats rows into CSV and writes file pointers. I think it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Format rows to CSV and write to file pointer Step 1: Open file pointer $file=fopen("path/to/file.csv","w"); Step 2: Convert rows to CSV string using fputcsv( ) function converts rows to CSV strings. The function accepts the following parameters: $file: file pointer $fields: CSV fields as an array $delimiter: field delimiter (optional) $enclosure: field quotes (

This article will explain in detail about changing the current umask in PHP. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Overview of PHP changing current umask umask is a php function used to set the default file permissions for newly created files and directories. It accepts one argument, which is an octal number representing the permission to block. For example, to prevent write permission on newly created files, you would use 002. Methods of changing umask There are two ways to change the current umask in PHP: Using the umask() function: The umask() function directly changes the current umask. Its syntax is: intumas

This article will explain in detail about PHP calculating the MD5 hash of files. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP calculates the MD5 hash of a file MD5 (MessageDigest5) is a one-way encryption algorithm that converts messages of arbitrary length into a fixed-length 128-bit hash value. It is widely used to ensure file integrity, verify data authenticity and create digital signatures. Calculating the MD5 hash of a file in PHP PHP provides multiple methods to calculate the MD5 hash of a file: Use the md5_file() function. The md5_file() function directly calculates the MD5 hash value of the file and returns a 32-character

This article will explain in detail how PHP truncates files to a given length. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Introduction to PHP file truncation The file_put_contents() function in PHP can be used to truncate files to a specified length. Truncation means removing part of the end of a file, thereby shortening the file length. Syntax file_put_contents($filename,$data,SEEK_SET,$offset);$filename: the file path to be truncated. $data: Empty string to be written to the file. SEEK_SET: designated as the beginning of the file

This article will explain in detail how PHP returns an array after key value flipping. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP Key Value Flip Array Key value flip is an operation on an array that swaps the keys and values in the array to generate a new array with the original key as the value and the original value as the key. Implementation method In PHP, you can perform key-value flipping of an array through the following methods: array_flip() function: The array_flip() function is specially used for key-value flipping operations. It receives an array as argument and returns a new array with the keys and values swapped. $original_array=[

This article will explain in detail the numerical encoding of the error message returned by PHP in the previous Mysql operation. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. . Using PHP to return MySQL error information Numeric Encoding Introduction When processing mysql queries, you may encounter errors. In order to handle these errors effectively, it is crucial to understand the numerical encoding of error messages. This article will guide you to use php to obtain the numerical encoding of Mysql error messages. Method of obtaining the numerical encoding of error information 1. mysqli_errno() The mysqli_errno() function returns the most recent error number of the current MySQL connection. The syntax is as follows: $erro

This article will explain in detail how PHP determines whether a specified key exists in an array. The editor thinks it is very practical, so I share it with you as a reference. I hope you can gain something after reading this article. PHP determines whether a specified key exists in an array: In PHP, there are many ways to determine whether a specified key exists in an array: 1. Use the isset() function: isset($array["key"]) This function returns a Boolean value, true if the specified key exists, false otherwise. 2. Use array_key_exists() function: array_key_exists("key",$arr

This article will explain in detail about obtaining pi in PHP. The editor thinks it is quite practical, so I share it with you as a reference. I hope you can gain something after reading this article. Introduction to Obtaining Pi with PHP Pi (π) is the ratio of the circumference to the diameter of a circle. It is an irrational number and cannot be expressed with a finite number of digits. In php, you can use the built-in function M_PI to get an approximate value of pi. M_PI function The M_PI function returns an approximate value of pi, accurate to 14 decimal places. It is a constant of PHP, so you don't need to use any parameters to use it. Syntax output 3.14159265358979 Alternative methods In addition to the M_PI function, there are some alternatives
