Home > Web Front-end > JS Tutorial > Mastering JWT (JSON Web Tokens): A Deep Dive

Mastering JWT (JSON Web Tokens): A Deep Dive

DDD
Release: 2025-01-21 20:37:10
Original
731 people have browsed it

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:

  1. The user sends the username and password to the server.
  2. After successful server authentication, user role, login time and other related data will be saved in the current session.
  3. The server returns a session_id to the user and writes it to the user's Cookie.
  4. Every subsequent request by the user will send the session_id back to the server through Cookie.
  5. 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:

<code class="language-json">{"name": "Alice", "role": "admin", "expiration time": "2024年7月1日0:00"}</code>
Copy after login
Copy after login

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:

Mastering JWT (JSON Web Tokens): A Deep Dive

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

Mastering JWT (JSON Web Tokens): A Deep Dive

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:

<code class="language-json">{"alg": "HS256", "typ": "JWT"}</code>
Copy after login
Copy after login

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:

<code class="language-json">{"name": "Alice", "role": "admin", "expiration time": "2024年7月1日0:00"}</code>
Copy after login
Copy after login

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:

<code class="language-json">{"alg": "HS256", "typ": "JWT"}</code>
Copy after login
Copy after login

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

Mastering JWT (JSON Web Tokens): A Deep Dive

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.

Mastering JWT (JSON Web Tokens): A Deep Dive

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template