What is the JWT

JSON Web Token (abbreviated JWT) is the most popular cross-domain authentication solution available today. It is composed of three parts, as shown in the following example, the detailed explanation is as follows (JWT does not have empty lines, the following is just for display, so it is more convenient to use a newline).

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjMfQ.
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
Copy the code

It consists of three parts separated by a “.”

The first part is the header information,

{

  "alg""HS256".// The encryption algorithm

  "typ""JWT"// For encryption, enter JWT

}

Copy the code

The second part is Payload, which consists of six fixed parts and custom data. The custom data needs to be defined according to its own situation, which can be omitted.

'iss'= >'https://www.qqdeveloper.com'./ / issue
'exp' => time() + 86400.// The validity period is 1 day.
'sub'= >'Subject Content'./ / theme
'aud'= >'Audience Content'./ / audience
'nbf'= >$time.// Effective time
'iat'= >$time.// Issue time
'jti'= >123./ / number

Copy the code

The third part is Signature(which is encrypted from the first two parts). Since the first two parts are open and transparent data, we need encryption to prevent data tampering and leakage. First, you need to specify a key (secret). This key is known only to the server and cannot be disclosed to the user. Then, using the signature algorithm specified in the Header (the default is HMAC SHA256), the following formula is used to generate the signature.

The first part of the encryption method (base64UrlEncode(header) +"." +
base64UrlEncode(payload),
secret)
Copy the code

The result is the long string above.

Why is JWT used

The traditional authentication mode is based on sessions and cookies to implement user authentication and authentication. The specific process pattern is shown in the following figure.

1. The client sends an HTTP request to the server.

< span style = “box-sizing: border-box; color: RGB (74, 74, 74); line-height: 22px; font-size: 16px; white-space: inherit! Important;” Of course, we can change the specific storage, such as database storage.

3. When the client receives the sessionid, it is stored in a cookie and carries the sessionid with each request.

4. After receiving the request from the client, the server implements authentication and authorization based on the sessionid sent by the client.

Here I also recommend my previous article about session and cookie knowledge. Session and cookie details

1. The client sends an HTTP request to the server.

2. The server generates a unique token after receiving the request from the client. <font color=’red’> The generated token needs to be stored on the server. It can also be stored in cached databases such as Redis and memcached.

3. The server returns the token to the client. The client saves the token in the request header, cookie, or localstorage.

4. When sending a request to the server, the server carries the token, and the server authenticates or authorizes the token.

1. The client sends an HTTP request to the server.

2. The server generates a token according to JWT generation rules and returns it to the client. <font color=’red’> The server does not need to store the token.

3. When the client receives the token, the client exists.

4. When the client sends a request to the server, the server parses the requested token. If the parsed data is consistent with the generated data, the server performs corresponding operations.

What are the pros and cons of session – and cookie-based authentication and authentication modes?

From the above figures, we can generally see that session-based storage is required by the server, while JWT does not need to be stored by the server. The above points are summarized as follows:

A and disadvantages

1. It is easy to encounter cross-domain problems. Different domain names cannot be directly authenticated through the session.

2. In a distributed deployment system, the shared session mechanism is required

3. CSRF problems are easy to occur.

Second, the advantages of

1. Convenient and flexible. The server creates a sessionid and sends it to the client.

2. Sessions are stored on the server, which is more secure.

3. The server can clear the session and authorize the user again.

What’s the difference between JWT and Session?

JWT is an authentication mode based on client storage, while session is an authentication mode based on server storage. Although JWT does not use server-side storage, it can also avoid cross-domain, CSRF and other situations. But there are also several not so good.

1. The authentication token cannot be cleared. Since the tokens generated by JWT are stored on the client, no server can take the initiative to clear them until the expiration time. Unless the server logic changes.

2. The storage device is stored on the client, which is less secure than that on the server. When the token generated by JWT is cracked, it is not easy to clear the token.

How to use JWT

Here I use firebase/ PHP-Jwt, directly used in the project can be installed successfully.

composer require firebase/php-jwt
Copy the code

Next, create a controller, which I use here in the ThinkPHP5.1 framework


use think\Controller;
use Firebase\JWT\JWT;

class Test extends Controller

{
    private $key'jwtKey';
    / / generated JWT
    public function createJwt()
    {
        $time= time();
        $key$this->key;
        $token= [
            'iss'= >'https://www.qqdeveloper.com'./ / issue
            'exp'= >$time86400.// The validity period is 1 day.
            'sub'= >'Subject Content'./ / theme
            'aud'= >'Audience Content'./ / audience
            'nbf'= >$time.// Effective time
            'iat'= >$time.// Issue time
            'jti'= >123./ / number
            // Additional custom data
            'data'= > ['userName'= >'Programming prodigal goes anywhere']]./ / call to generate encryption method (' Payloadn content ', 'encryption keys, [' encryption algorithms'], [' encryption can'], [' JWT header head])
        $jwt= JWT::encode($token.$key);
        return json(['data'= >$jwt]);
    }
    / / parsing JWT
    public function analysisJwt()
    {
        try {
            $key$this->key;
            $jwt'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLm9yZyIsImV4cCI6MTU2ODA5NjE4MCwic3ViIjoiXHU0ZTNiXH U5ODk4XHU1MTg1XHU1YmI5IiwiYXVkIjoiXHU1M2Q3XHU0ZjE3XHU1MTg1XHU1YmI5IiwibmJmIjoxNTY4MDA5NzgwLCJpYXQiOjE1NjgwMDk3ODAsImp0aS I6MTIzLCJkYXRhIjp7InVzZXJOYW1lIjoiXHU3ZjE2XHU3YTBiXHU2ZDZhXHU1YjUwXHU4ZDcwXHU1NmRiXHU2NWI5In19.kHb_9Np0zjE25YE9czUEGvmFP YtqMJT9tuZzJTuMZl0';
            // Call the decryption method ('JWT content ',' decrypted key, and encrypted key all the way ',' encryption algorithm ')
            $decoded= JWT::decode($jwt.$key.array('HS256'));
            return json(['message'= >$decoded]);
        } catch (\Exception $exception) {
            return json(['message'= >$exception->getMessage()]); }}}Copy the code

By accessing the first method, you can generate the string shown belowWe copy the string from the figure above into the $JWT variable in the second figure, and access the second method to parse out the specific data.