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:
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>
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:
One line is expressed as: Header.Payload.Signature
These three parts are introduced below.
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>
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).
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:
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>
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.
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>
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.
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
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!