Home >Web Front-end >JS Tutorial >In-depth analysis of the principles and usage of JWT (JSON Web Token)

In-depth analysis of the principles and usage of JWT (JSON Web Token)

藏色散人
藏色散人forward
2023-01-10 10:55:211932browse

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.

In-depth analysis of the principles and usage of JWT (JSON Web Token)

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.

In-depth analysis of the principles and usage of JWT (JSON Web Token)

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

In-depth analysis of the principles and usage of JWT (JSON Web Token)

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

In addition to the official fields, You can also define private fields in this section, here is an example.

{
  "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!

Statement:
This article is reproduced at:码农编程进阶笔记. If there is any infringement, please contact admin@php.cn delete