[Cross-domain authentication] Explain JWT in detail, what is JWT?

JSON Web Token (abbreviated as JWT) is currently the most popular cross-domain authentication solution. This article introduces its principle and usage.

1. The problem of 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 is authenticated, save relevant data in the current session (session), such as user role, login time, etc.

3. The server returns a session_id to the user and writes it into the user's Cookie.

4. For each subsequent request of the user, the session_id will be sent back to the server through the cookie.

5. The server receives the session_id, finds the data saved in the previous period, and thus knows the identity of the user.

The problem with this model is that the scalability (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 affiliated 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 session data persistence, written to a database or other persistence layer. After receiving the request, various services request data from the persistence layer. The advantage of this scheme is that the structure is clear, and the disadvantage is that the amount of engineering is relatively large. In addition, if the persistence layer hangs up, it will be a single point of failure.

Another solution is that the server does not save session data at all, and all data is saved on the client, and each request is sent back to the server. JWT is a representative of this kind of scheme.

2. The principle of JWT

The principle of JWT is that after the server is authenticated, a JSON object is generated and sent 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 must be sent back. The server completely relies 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, that is to say, the server becomes stateless, which makes it easier to expand.

3. The data structure of JWT

The actual JWT looks like the following.

It is a long string .separated into three parts by dots ( ). Note that there is no line break inside the JWT. Here it is written in several lines just for the sake of display.

The three parts of a JWT are as follows, in order.

  • Header
  • Payload
  • Signature

Written in one line, it looks like the following.


Header.Payload.Signature

These three parts are described in turn below.

3.1 Header

The Header part is a JSON object that describes the metadata of the JWT, usually as follows.


{
  "alg": "HS256",
  "typ": "JWT"
}

In the above code, algthe attribute indicates the signature algorithm (algorithm), the default is HMAC SHA256 (written as HS256); the typattribute indicates the type of the token (token), and the JWT token is uniformly written as JWT.

Finally, use the Base64URL algorithm (see below) to convert the above JSON object into a string.

3.2 Payload

The Payload part is also a JSON object, which is used to store the actual data that needs to be passed. JWT specifies 7 official fields for selection.

  • iss (issuer): Issuer
  • exp (expiration time): expiration time
  • sub (subject): subject
  • aud (audience): audience
  • nbf (Not Before): effective time
  • iat (Issued At): Issue time
  • jti (JWT ID): number

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


{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

Note that JWT is unencrypted by default and can be read by anyone, so don't put secret information in this section.

This JSON object should 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 key (secret). This key is known only to the server and cannot be disclosed to the user. Then, use the signature algorithm specified in the Header (the default is HMAC SHA256), and generate a signature according to the following formula.


HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

After calculating the signature, combine the three parts of Header, Payload and Signature into a string, and separate each part with a "dot" ( .), and then return it to the user.

3.4 Base64URL

As mentioned earlier, the algorithm for serialization of Header and Payload is Base64URL. This algorithm is basically similar to the Base64 algorithm, but there are some minor differences.

JWT is used as a token (token), which may be placed in the URL in some occasions (such as api.example.com/?token=xxx). Base64 has three characters +, /and =, which have special meanings in the URL, so they must be replaced: =omitted, +replaced with -, /replaced with _ . This is the Base64URL algorithm.

4. How to use JWT

The client receives the JWT returned by the server, which can be stored in Cookie or localStorage.

After that, every time the client communicates with the server, it must bring this JWT. You can put it in the cookie and send it automatically, but this cannot cross domains, so it is better to put it in the header information Authorizationfield of the HTTP request.


Authorization: Bearer <token>

Another approach is that when crossing domains, JWT is placed in the data body of the POST request.

Five, several characteristics of JWT

(1) JWT is not encrypted by default, but it can also 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 into JWT.

(3) JWT can be used not only for authentication, but also for exchanging information. Effective use of JWT can reduce the number of times the server queries the database.

(4) The biggest disadvantage of JWT is that since the server does not save the session state, it is impossible to revoke a token or change the permission of the token during use. That is, once a JWT is issued, it will remain valid until it expires, unless the server deploys additional logic.

(5) JWT itself contains authentication information, once leaked, anyone can obtain all permissions of the token. In order to reduce misappropriation, the validity period of JWT should be set relatively short. For some more important permissions, the user should be authenticated again when using it.

(6) In order to reduce misappropriation, JWT should not be transmitted in plain text using the HTTP protocol, but should be transmitted using the HTTPS protocol.

Guess you like

Origin blog.csdn.net/wufaqidong1/article/details/131543755