当前位置:网站首页>Actual combat simulation │ JWT login authentication
Actual combat simulation │ JWT login authentication
2022-07-05 01:02:00 【Geek flying rabbit】
Token The certification process
- As the most popular cross domain authentication solution ,
JWT(JSON Web Token)Loved by developers , The main process is as follows : - The client sends an account and password to request login
- The server receives the request , Verify whether the account and password pass
- After successful verification , The server will generate a unique
token, And return it to the client - Client received
token, Store it incookieperhapslocalStrogein - After that, every time the client sends a request to the server , Will pass
cookieperhapsheaderTake with youtoken - Server side validation
tokenThe effectiveness of the , The data of the response is returned only after passing

Token Certification benefits
- Support cross domain access :
CookieCross domain access is not allowed , That's rightTokenThere is no mechanism , The premise is that the transmitted user authentication information passesHTTPHead transmission - No state :
TokenThe mechanism does not need storage on the serversessionInformation , becauseTokenIt contains the information of all users who log in , Just on the client sidecookieOr local media storage status information - More applicable : As long as it's support
httpProtocol client , You can usetokenauthentication . - Don't need to consider CSRF: Because no longer rely on
cookie, So usingtokenThe authentication method will not happenCSRF, So there is no need to considerCSRFDefense
JWT structure
- One
JWTIt's actually a string , It consists of three parts :Head、loadAndSignature. Middle point.Divided into three parts . Be carefulJWTThere is no line break inside .

- Head / header
headerIt's made up of two parts :tokenThe type ofJWTAnd algorithm name :HMAC、SHA256、RSA
{
"alg": "HS256",
"typ": "JWT"
}
- load / Payload
PayloadPart of it is also aJSONobject , It is used to store the data that needs to be transferred .JWTSpecify seven default fields to choose from .- In addition to the default fields , You can add any field you want , Generally, after the user logs in successfully , Store user information here
iss: The issuer
exp: Due time
sub: The theme
aud: user
nbf: Not available until
iat: Release time
jti:JWT ID Used to identify the JWT
{
"iss": "xxxxxxx",
"sub": "xxxxxxx",
"aud": "xxxxxxx",
"user": [
'username': ' Geek flying rabbit ',
'gender': 1,
'nickname': ' Flying rabbit '
]
}
- Signature / Signature
- The signature part is on the above Head 、 load Data signature with two parts of data
- To ensure that the data is not tampered with , You need to specify a key , And this key is usually only known by you , And stored on the server
- The code to generate the signature is generally as follows :
// among secret It's the key
String signature = HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
JWT Basic use
- The client receives the
JWT, Can be stored inCookieInside , It can also be stored inlocalStorage - then Every time the client communicates with the server , Take this with you
JWT - hold
JWTSave inCookieSend request inside , It can't beCross domain - It's better to put it in
HTTPRequested header informationAuthorizationIn the field
fetch('license/login', {
headers: {
'Authorization': 'X-TOKEN' + token
}
})
actual combat : Use JWT Login authentication
Use here
ThinkPHP6IntegrateJWTLogin and authenticate for actual combat simulationinstall JWT Expand
composer require firebase/php-jwt
- Package generation JWT And decryption methods
<?php
/** * Desc: JWT authentication * Author: autofelix * Time: 2022/07/04 */
namespace app\services;
use app\Helper;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
class JwtService
{
protected $salt;
public function __construct()
{
// Get a unique string from the configuration information , You can write whatever you like md5('token')
$this->salt = config('jwt.salt') || "autofelix";
}
// jwt Generate
public function generateToken($user)
{
$data = array(
"iss" => 'autofelix', // Issuer Can be null
"aud" => 'autofelix', // Face users , Can be null
"iat" => Helper::getTimestamp(), // The issuance of time
"nbf" => Helper::getTimestamp(), // Take effect immediately
"exp" => Helper::getTimestamp() + 7200, //token Expiration time Two hours
"user" => [ // Record user information
'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 Decrypt
public function chekToken($token)
{
JWT::$leeway = 60; // Subtract... From the current time 60, Leave some room for time
$decoded = JWT::decode($token, new Key(md5($this->salt), 'HS256'));
return $decoded;
}
}
- After the user logs in , Generate JWT identification
<?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']);
// .... Relevant logic for verification ...
$user = UserModel::where('username', $data['username'])->find();
// Verify by generating JWT, Return to front end save
$token = (new JwtService())->generateToken($user);
return json([
'code' => ResponseCode::SUCCESS,
'message' => ' Login successful ',
'data' => [
'token' => $token
]
]);
}
}
- Middleware verifies whether the user logs in
- stay
middleware.phpRegister middleware
<?php
// Global middleware definition file
return [
// ... Other middleware
// JWT verification
\app\middleware\Auth::class
];
- After registering middleware , Improve the verification logic in the permission verification middleware
<?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 verification
$jwt = (new JwtService())->chekToken($token);
} catch (\Throwable $e) {
return json([
'code' => ResponseCode::ERROR,
'msg' => 'Token Validation failed '
]);
}
$request->user = $jwt->user;
}
return $next($request);
}
}
边栏推荐
- 4. Scala writes HelloWorld in idea, in-depth analysis of accompanying objects, and association of source packages
- There is a new Post-00 exam king in the testing department. I really can't do it in my old age. I have
- Huawei employs millions of data governance experts! The 100 billion market behind it deserves attention
- dotnet-exec 0.6.0 released
- 6. Scala operator
- [wave modeling 1] theoretical analysis and MATLAB simulation of wave modeling
- 2022.07.03 (LC 6109 number of people who know secrets)
- Basic operation of database and table ----- the concept of index
- What did I pay for it transfer to testing post from confusion to firmness?
- const、volatile和restrict的作用和用法总结
猜你喜欢

SAP ui5 application development tutorial 107 - trial version of SAP ui5 overflow toolbar container control introduction
![[wave modeling 2] three dimensional wave modeling and wave generator modeling matlab simulation](/img/50/b6cecc95e46fe1e445eb00ca415669.png)
[wave modeling 2] three dimensional wave modeling and wave generator modeling matlab simulation

SAP UI5 应用的主-从-从(Master-Detail-Detail)布局模式的实现步骤

107. SAP UI5 OverflowToolbar 容器控件以及 resize 事件处理的一些细节介绍

Talking about JVM 4: class loading mechanism

整理混乱的头文件,我用include what you use

Apifox (postman + swagger + mock + JMeter), an artifact of full stack development and efficiency improvement

Basic operation of database and table ----- the concept of index

107. Some details of SAP ui5 overflow toolbar container control and resize event processing

【纯音听力测试】基于MATLAB的纯音听力测试系统
随机推荐
Introduction to the gtid mode of MySQL master-slave replication
Daily question brushing record (13)
Playwright之录制
Deux nombres se remplacent
SAP ui5 application development tutorial 107 - trial version of SAP ui5 overflow toolbar container control introduction
Analysis and comparison of leetcode weekly race + acwing weekly race (t4/t3)
There is a new Post-00 exam king in the testing department. I really can't do it in my old age. I have
Huawei employs millions of data governance experts! The 100 billion market behind it deserves attention
SAP UI5 应用开发教程之一百零七 - SAP UI5 OverflowToolbar 容器控件介绍的试读版
Basic operations of database and table ----- delete index
大专学历,33岁宝妈又怎样?我照样销售转测试,月入13k+
Two numbers replace each other
The performance of major mainstream programming languages is PK, and the results are unexpected
Detailed explanation of multi-mode input event distribution mechanism
What happened to those who focused on automated testing?
107. SAP UI5 OverflowToolbar 容器控件以及 resize 事件处理的一些细节介绍
Insert sort of sort
Maximum number of "balloons"
What did I pay for it transfer to testing post from confusion to firmness?
揭露测试外包公司,关于外包,你或许听到过这样的声音