thinkphp6 uses jwt to generate token middleware to verify token

 

jwt and tp middleware sound very tall.

It took two days to read the documents and watch the video. I finally got a little understanding. I'll record it here.

The following two questions need to be understood

1 what is jwt?

JWT is a json based open standard (RFC 7519), which is designed as a compact and secure single sign on (SSO) scenario for distributed sites. JWT declaration is generally used to pass the authenticated user identity information between identity provider and service provider, so as to obtain resources from the server. It can also add some additional declaration information necessary for other business logic. The token can also be used for authentication or encryption.

In short, what we need here is the encryption and decryption of jwt.

 

Let's make a brief record

The first step is to install the jwt extension

It is recommended to use composer to install conveniently and quickly

composer require firebase/php-jwt

 

After successful operation, figure 1 and Figure 2 are displayed, that is, the installation is successful:

 

Chart 1:

 

Fig. two:

 

 

The second step calls the encode and decode methods in JWT to generate token and verify token

 

I used the common.php file under the app directory to make a public method

First, JWT is introduced, and then two methods are written to generate signature verification and verification token.

use \Firebase\JWT\JWT;
//Generate check
function signToken($uid){
    $key='!@#$% * & '; / / this is a custom random string that should be written in the config file. It will also be used for decryption, which is equivalent to the salt salt commonly used in encryption
    $token=array(
        "iss"=>$key,        //Issuer can be empty
        "aud"=>'',          //User of face image, can be empty
        "iat"=>time(),      //Time filed
        "nbf"=>time()+3,    //When does jwt take effect (here, it takes 100 seconds for the generation to take effect)
        "exp"=> time()+200, //token expiration time
        "data"=>[           //The recorded userid information is added by itself here. If there is any other information, you can add the key value pair of the array
            'uid'=>$uid,
        ]
    );
    //  print_r($token);
    $jwt = JWT::encode($token, $key, "HS256");  //token is generated according to parameters
    return $jwt;
}

}

//Verify token
function checkToken($token){
    $key='!@#$%*&'; 
    $status=array("code"=>2);
    try {
        JWT::$leeway = 60;//Subtract 60 from the current time to make room for it
        $decoded = JWT::decode($token, $key, array('HS256')); //HS256 mode, which corresponds to the time of issuing
        $arr = (array)$decoded;
        $res['code']=1;
        $res['data']=$arr['data'];
        return $res;

    } catch(\Firebase\JWT\SignatureInvalidException $e) { //Incorrect signature
        $status['msg']="Incorrect signature";
        return $status;
    }catch(\Firebase\JWT\BeforeValidException $e) { // Signature cannot be used until a certain point in time
        $status['msg']="token Invalid";
        return $status;
    }catch(\Firebase\JWT\ExpiredException $e) { // token expired
        $status['msg']="token Invalid";
        return $status;
    }catch(Exception $e) { //Other mistakes
        $status['msg']="unknown error";
        return $status;
    }
}

 

Step 3: use.

Generate token. Here is to encrypt the user id. of course, you can add other parameters, such as ip, mobile number, account name, etc. Pass the information to be encrypted to the singToken method.

$user['token'] = signToken($user['id']);


// token return value 

//eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJtZGMhQCMkIiwiYXVkIjoiIiwiaWF0IjoxNTc5MTU3OTY4LCJuYmYiOjE1NzkxNTc5NzEsImV4cCI6MTU3OTE1ODE2OCwiZGF0YSI6eyJ1aWQiOjV9fQ.mFdRYr_sf63U5STJoxfOFFRyJj8V4N_h-sx3hQcZ2qk

Verify the token. The token here is generally transmitted in the header mode. After receiving, directly call the checkToken method of the common.php file. The encrypted token information is returned after verification. The verification fails and a prompt message is returned.

$token = Request::instance()->header('token');
$res = checkToken($token);

 

 

 

 

37 original articles published, 3 praised, 10000 visitors+
Private letter follow

Tags: PHP JSON Mobile

Posted on Thu, 16 Jan 2020 02:49:23 -0800 by osiris1603