Mastering JWT (JSON Web Tokens): A Deep Dive
JSON Web Token (JWT): a popular solution for cross-domain authentication
This article introduces the principles and usage of JSON Web Token (JWT), the most popular cross-domain authentication solution at the moment.
1. Challenges of cross-domain authentication
Internet services are inseparable from user authentication. The traditional process is as follows:
- The user sends the username and password to the server.
- After successful server authentication, user role, login time and other related data will be saved in the current session.
- The server returns a session_id to the user and writes it to the user's Cookie.
- Every subsequent request by the user will send the session_id back to the server through Cookie.
- After the server receives the session_id, it looks for the pre-saved data to identify the user.
This model has poor scalability: a single-machine environment is fine, but a server cluster or a cross-domain service-oriented architecture requires session data sharing, and each server can read the session. For example, website A and website B are related services of the same company. After users log in to one of the websites, they can automatically log in when they visit the other website. One solution is to persist the session data, write it to a database or other persistence layer, and request the data from the persistence layer after each service receives the request. This solution has a clear architecture, but the workload is large, and persistence layer failure will lead to a single point of failure. Another option is that the server does not save session data at all, all data is saved on the client and sent back to the server with every request. JWT represents this approach.
2. Principle of JWT
The principle of JWT is that the server generates a JSON object after verification and returns it to the user, for example:
{"name": "Alice", "role": "admin", "expiration time": "2024年7月1日0:00"}
Later, when the user communicates with the server, this JSON object needs to be returned, and the server completely determines the user's identity based on this object. To prevent users from tampering with data, the server adds a signature when generating this object (details described later). The server no longer saves any session data, that is, the server becomes stateless and easier to scale.
3. JWT data structure
The actual JWT looks like this:
It is a long string separated into three parts by dots (.). Note that there are no line breaks inside the JWT, the line breaks here are just for ease of display. The three parts of JWT are as follows:
- Header
- Payload
- Signature
One line is expressed as: Header.Payload.Signature
These three parts are introduced below.
3.1 Header
The Header part is a JSON object describing the metadata of the JWT, usually as follows:
{"alg": "HS256", "typ": "JWT"}
The alg attribute represents the signature algorithm, the default is HMAC SHA256 (HS256); the typ attribute represents the type of this token, and JWT tokens are uniformly written as JWT. This JSON object is ultimately converted to a string using the Base64URL algorithm (details below).
3.2 Payload
The Payload part is also a JSON object used to store the actual data that needs to be transmitted. JWT defines 7 official optional fields:
- iss (issuer): Issuer
- exp (expiration time): expiration time
- sub (subject): subject
- aud (audience): audience
- nbf (Not Before): effective time
- iat (Issued At):Issuance time
- jti (JWT ID): serial number
In addition to official fields, private fields can also be customized. For example:
{"name": "Alice", "role": "admin", "expiration time": "2024年7月1日0:00"}
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 also needs to be converted to a string using the Base64URL algorithm.
3.3 Signature
The Signature part is the signature of the first two parts, used to prevent data tampering. First, you need to specify a secret. This secret is only known by the server and cannot be leaked to the user. Then use the signature algorithm specified in the Header (default is HMAC SHA256) to generate a signature according to the following formula:
{"alg": "HS256", "typ": "JWT"}
After the signature is calculated, the three parts Header, Payload and Signature are combined into a string, and each part is separated by "dot" (.), which can be returned to the user.
3.4 Base64URL
As mentioned earlier, the serialization algorithm of Header and Payload is Base64URL. This algorithm is basically similar to the Base64 algorithm, but has some minor differences. As a token, JWT may sometimes be placed in a URL (such as api.example.com/?token=xxx). The three characters in Base64, / and = have special meanings in the URL and need to be replaced: = is omitted and replaced by Replaced with -, / is replaced with _. This is the Base64URL algorithm.
4. How to use JWT
After the client receives the JWT returned by the server, it can store it in Cookie or localStorage. The client needs to carry this JWT every time it communicates with the server. It can be placed in a cookie and sent automatically, but this cannot be done across domains. A better approach is to put it in the Authorization field of the HTTP request header:
Authorization: Bearer
Another approach is to put the JWT in the body of the POST request when crossing domains.
5. Several characteristics of JWT
(1) JWT is not encrypted by default, but can be encrypted. After the original Token is generated, it can be encrypted again with the key.
(2) If JWT is not encrypted, secret data cannot be written.
(3) JWT can be used not only for identity verification, but also for information exchange. Effective use of JWT can reduce the number of times the server queries the database.
(4) The biggest disadvantage of JWT is that the server does not save the session state and cannot revoke a token or change the token's permissions during use. That is, once a JWT is issued, it remains valid until it expires unless the server deploys additional logic.
(5) The JWT itself contains authentication information, and once leaked, anyone can obtain all permissions of the token. To reduce theft, the validity period of JWT should be set relatively short. For some more important permissions, users should authenticate again when using them.
(6) To reduce theft, JWT should not be transmitted in clear text using HTTP protocol, but should be transmitted using HTTPS protocol.
Leapcell: The Best Serverless Web Hosting Platform
Finally, I recommend the best platform for deploying web services: Leapcell
1. Multi-language support
- Develop in JavaScript, Python, Go or Rust.
2. Deploy unlimited projects for free
- Pay only for what you use – no requests, no fees.
3. Unparalleled cost-effectiveness
- Pay as you go, no idle fees.
- Example: $25 supports 6.94 million requests with an average response time of 60ms.
4. Simplified developer experience
- Intuitive UI, easy to set up.
- Fully automated CI/CD pipeline and GitOps integration.
- Real-time metrics and logging for actionable insights.
5. Easy expansion and high performance
- Automatic expansion to easily handle high concurrency.
- Zero operational overhead - just focus on building.
Learn more in the documentation!
Leapcell Twitter: https://www.php.cn/link/7884effb9452a6d7a7a79499ef854afd
The above is the detailed content of Mastering JWT (JSON Web Tokens): A Deep Dive. 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

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)

Hot Topics

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
