In-depth analysis of the principles and usage of JWT (JSON Web Token)
This article brings you relevant knowledge about JWT. It mainly introduces what is JWT? What is the principle and usage of JWT? For those who are interested, let’s take a look below. I hope it will be helpful to everyone.

JSON Web Token (abbreviated as JWT) is currently the most popular cross-domain authentication solution. This article introduces its principles and usage.
1. Issues with cross-domain authentication
Internet services are inseparable from user authentication. The general process is as follows.
1. The user sends the user name and password to the server.
2. After the server verification is passed, relevant data, such as user role, login time, etc., will be saved in the current session.
3. The server returns a session_id to the user and writes it into the user's Cookie.
4. Each subsequent request by the user will pass the session_id back to the server through Cookie.
5. The server receives the session_id, finds the data saved in the previous stage, and learns the user's identity.
The problem with this model is that the scaling is not good. Of course, there is no problem with a single machine. If it is a server cluster or a cross-domain service-oriented architecture, session data sharing is required, and each server can read the session.
For example, website A and website B are related services of the same company. Now it is required that as long as the user logs in on one of the websites, he will automatically log in when he visits another website. How can this be achieved?
One solution is to persist session data and write it to the database or other persistence layer. After receiving the request, various services request data from the persistence layer. The advantage of this solution is that the structure is clear, but the disadvantage is that the amount of work is relatively large. In addition, if the persistence layer fails, it will be a single point of failure.
Another solution is that the server simply does not save the session data. All data is saved on the client and sent back to the server for each request. JWT is a representative of this solution.
2. The principle of JWT
The principle of JWT is that after the server authenticates, it generates a JSON object and sends it back to the user, as shown below.
{
"姓名": "张三",
"角色": "管理员",
"到期时间": "2018年7月1日0点0分"
}In the future, when the user communicates with the server, this JSON object will be sent back. The server relies solely on this object to identify the user. In order to prevent users from tampering with data, the server will add a signature when generating this object (see below for details).
The server does not save any session data. In other words, the server becomes stateless, making it easier to expand.
3. JWT data structure
The actual JWT is probably as follows.

It is a very long string separated into three parts by a dot (.) in the middle. Note that there is no line break inside the JWT. It is written in several lines just for the convenience of display.
The three parts of JWT are as follows.
Header
Payload
Signature
Write it in one line, as shown below.
Header.Payload.Signature

The following will introduce these three parts in turn.
3.1 Header
The Header part is a JSON object describing the metadata of the JWT, usually as follows.
{
"alg": "HS256",
"typ": "JWT"
}In the above code, the alg attribute represents the signature algorithm (algorithm), the default is HMAC SHA256 (written as HS256); the typ attribute represents the type of the token (token), and the JWT token is written uniformly for JWT.
Finally, convert the above JSON object into a string using the Base64URL algorithm (see below for details).
3.2 Payload
The Payload part is also a JSON object, used to store the actual data that needs to be transferred. JWT specifies 7 official fields for selection.
iss (issuer): issuer
exp (expiration time): expiration time
sub (subject): Topic
aud (audience): Audience
- ##nbf (Not Before): Effective time
- iat (Issued At): Issuance time
- jti (JWT ID): Number
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}Note that JWT is not encrypted by default and can be read by anyone, so do not put secret information in this section. This JSON object must also be converted into a string using the Base64URL algorithm.
3.3 Signature
The Signature part is the signature of the first two parts to prevent data tampering. First, you need to specify a secret. This key is known only to the server and cannot be leaked to users. Then, use the signature algorithm specified in the Header (the default is HMAC SHA256) to generate a signature according to the following formula.HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
算出签名以后,把 Header、Payload、Signature 三个部分拼成一个字符串,每个部分之间用"点"(.)分隔,就可以返回给用户。
3.4 Base64URL
前面提到,Header 和 Payload 串型化的算法是 Base64URL。这个算法跟 Base64 算法基本类似,但有一些小的不同。
JWT 作为一个令牌(token),有些场合可能会放到 URL(比如 api.example.com/?token=xxx)。Base64 有三个字符+、/和=,在 URL 里面有特殊含义,所以要被替换掉:=被省略、+替换成-,/替换成_ 。这就是 Base64URL 算法。
四、JWT 的使用方式
客户端收到服务器返回的 JWT,可以储存在 Cookie 里面,也可以储存在 localStorage。
此后,客户端每次与服务器通信,都要带上这个 JWT。你可以把它放在 Cookie 里面自动发送,但是这样不能跨域,所以更好的做法是放在 HTTP 请求的头信息Authorization字段里面。
Authorization: Bearer <token>
另一种做法是,跨域的时候,JWT 就放在 POST 请求的数据体里面。
五、JWT 的几个特点
(1)JWT 默认是不加密,但也是可以加密的。生成原始 Token 以后,可以用密钥再加密一次。
(2)JWT 不加密的情况下,不能将秘密数据写入 JWT。
(3)JWT 不仅可以用于认证,也可以用于交换信息。有效使用 JWT,可以降低服务器查询数据库的次数。
(4)JWT 的最大缺点是,由于服务器不保存 session 状态,因此无法在使用过程中废止某个 token,或者更改 token 的权限。也就是说,一旦 JWT 签发了,在到期之前就会始终有效,除非服务器部署额外的逻辑。
(5)JWT 本身包含了认证信息,一旦泄露,任何人都可以获得该令牌的所有权限。为了减少盗用,JWT 的有效期应该设置得比较短。对于一些比较重要的权限,使用时应该再次对用户进行认证。
(6)为了减少盗用,JWT 不应该使用 HTTP 协议明码传输,要使用 HTTPS 协议传输。
推荐学习:《JavaScript视频教程》
The above is the detailed content of In-depth analysis of the principles and usage of JWT (JSON Web Token). For more information, please follow other related articles on the PHP Chinese website!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft






