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 in cookie perhaps localStroge in
  • After that, every time the client sends a request to the server , Will pass cookie perhaps header Take with you token
  • Server side validation token The effectiveness of the , The data of the response is returned only after passing

be based on Token The certification process

Token Certification benefits

  • Support cross domain access :Cookie Cross domain access is not allowed , That's right Token There is no mechanism , The premise is that the transmitted user authentication information passes HTTP Head transmission
  • No state :Token The mechanism does not need storage on the server session Information , because Token It contains the information of all users who log in , Just on the client side cookie Or local media storage status information
  • More applicable : As long as it's support http Protocol client , You can use token authentication .
  • Don't need to consider CSRF: Because no longer rely on cookie, So using token The authentication method will not happen CSRF, So there is no need to consider CSRF Defense

JWT structure

  • One JWT It's actually a string , It consists of three parts : Head load And Signature . Middle point . Divided into three parts . Be careful JWT There is no line break inside .

JWT structure
  • Head / header
  • header It's made up of two parts : token The type of JWT And algorithm name :HMACSHA256RSA
{
"alg": "HS256",
"typ": "JWT"
}
  • load / Payload
  • Payload Part of it is also a JSON object , It is used to store the data that needs to be transferred .JWT Specify 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 in Cookie Inside , It can also be stored in localStorage
  • then Every time the client communicates with the server , Take this with you JWT
  • hold JWT Save in Cookie Send request inside , It can't be Cross domain
  • It's better to put it in HTTP Requested header information Authorization In the field
fetch('license/login', {
headers: {
'Authorization': 'X-TOKEN' + token
}
})

actual combat : Use JWT Login authentication

  • Use here ThinkPHP6 Integrate JWT Login and authenticate for actual combat simulation

  • install 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.php Register 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);
}
}

Live simulation │JWT More articles about login authentication

  1. 【 Project practice 】 One article will take you through Session and JWT How to login and authenticate

    Project driven learning , Test true knowledge with practice Preface Login authentication , It's probably the most common function of all systems , And it's the most basic . The most important feature . In order to do this well, many security frameworks have been born , For example, the most common Shiro.Spring Security ...

  2. OAuth2.0 actual combat ! Use JWT The token authentication !

    Hello everyone , I'm not just Chen ~ This is a <Spring Security Advanced > Of the 3 An article , Previous articles are as follows : actual combat !Spring Boot Security+JWT Front end and back end separate architecture login authentication ! Sister never ...

  3. be based on jwt User login authentication for

    Recently app In the development process , Made a base on token User login authentication for , Use vue+node+mongoDB Development in progress , To sum up . token The certification process : 1: The user enters the user name and password , Log in , Send a login letter ...

  4. Luffy Login authentication and JWT

    1. User authentication We've done it up front , Build the front-end login page , And routing assignment , Now let's do something about login authentication Django Provides an authentication system . The authentication system contains : user jurisdiction : binary ( yes / no ) Flag indicates whether a user can do ...

  5. be based on JWT Of Token Login authentication ( One )

    1.JWT brief introduction JSON Web Token( abbreviation JWT), Is the most popular cross domain authentication solution . session Login authentication scheme : The user passes the user name from the client . Password and other information , After authentication, the server stores the information in session in ...

  6. JWT Implement login authentication instance

    JWT Full name JSON Web Token, It's a compact , Self contained , Secure information exchange protocol .JWT There are many applications , For example, authority authentication , Information exchange, etc . This article will briefly introduce JWT An instance operation of login authority authentication . JWT form JW ...

  7. severe ! The interns I took just four steps to integrate SpringSecurity+JWT Realize login authentication !

    The sophomore is a new intern , As technology leader, I'm still very responsible , I want to throw any pot to him , ah , No , How can you say all your heart when you're not careful ? again ! The sophomore is a new intern , As technology leader, I'm still very responsible , what are you having? ...

  8. 10 Minutes of simple learning net core Integrate jwt Permission authentication , The quick access project is put into use

    What is? JWT JSON Web Token(JWT) Is currently the most popular cross domain authentication . Distributed login . Solutions such as single sign on . JWT Official website :https://jwt.io/ Generally speaking ,JWT It can represent the identity of users ...

  9. ASP.NET Core be based on JWT Certification of ( Two )

    ASP.NET Core be based on JWT Certification of ( Two ) We were right about Jwt Some of the basic knowledge of a simple introduction , In this section, we will explain in detail , This time we will introduce in detail Jwt stay .Net Core The practical application of ...

  10. ASP.NET Core be based on JWT Certification of ( One )

    ASP.NET Core be based on JWT Certification of ( One ) Json web token (JWT), Is a kind of implementation based on the JSON Open standards for ((RFC 7519). The token Be designed ...

Random recommendation

  1. ASP.NET MVC5+EF6+EasyUI Background management system (59)-BLL Layer refactoring

    Series catalog Preface :   This should be the last refactoring of the system , Will refactor BLL Layer and the Model layer . To completely replace the code generator generated BLL Layer and the DAL layer . It's completely useless for the code generator DAL,BLL,MODEL layer .   Full automatic generation of , Delete , Change ...

  2. HTTP POST Request message format analysis and Java File upload

    Time  2014-12-11 12:41:43  CSDN Blog original text   http://blog.csdn.net/bboyfeiyu/article/details/41863951 The theme  HTTPHt ...

  3. HDMI Study

    Most of them are on the market 4K The monitors are equipped with HDMI 1.4 Interface , Can only achieve 30Hz The refresh rate of , Not enough to bring smooth display effect , Dark purple condition , Even if it's a match HDMI 2.0 HD cable is also unable to play its role . Only more advanced HDMI 2.0 standard ...

  4. android AsyncTask Download and update the progress bar asynchronously

    AsyncTask Download and update the progress bar asynchronously    // If you don't understand, please see the asynchronous download in the last article AsyncTask<String, Integer, String> The first parameter :String Pass in ...

  5. Android in Handle Detailed explanation

    The above figure is my summary Handler, I found a blog with a good summary on the Internet copy To come over : As a reference Handler What's the use ? How to use ? One .Handler Functions and concepts Including thread queue and message queue , Implement asynchronous message processing mechanism , ...

  6. Android Custom scoring control :RatingStarView

    RatingStarView Android Custom scoring control , similar ProgressBar Like that , Use the star icon (full.half.empty) As progress Marking / Scoring control . design sketch chart 1: ...

  7. 【 Reprint 】 ISO14229 One of series : brief introduction

    Reprint link :http://www.cnblogs.com/autogeek/p/4458591.html Preface Because it is often used in work ISO-14229, Therefore, it is decided to make an overall introduction and summary of the agreement , It's about learning from yourself ...

  8. solve Skyline 6.5 In the version 3DML The problem of external web page hooking after model monomer

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  9. ubuntu Modify the user name and modify home The corresponding directory name

    1. Create a new user user2 sudo adduser temporary sudo adduser temporary sudo 2. from user1 logout. Enter new user user2, modify use ...

  10. Git HEAD A detailed explanation of the meaning And version fallback

    First ,Git You have to know which version the current version is , stay git in , use HEAD Represents the current version , That is, the latest submission 3628164...882e1e0( Pay attention to my submission ID It must be different from yours ), The last version was HEAD^, Last version ...