Initial knowledge of jwt in php

Keywords: JSON PHP

Using token to authenticate
1. Client logs in with account password
2. The server receives the request and verifies the correctness of the account and password. If it is correct, the server sends back a Token.
3. The client receives Token and stores it. Every time it accesses, it needs to carry token.
4. The server needs to verify token validity when it receives the client's request, and return the data if the validation is successful.

There are many ways to generate and validate token. We use jwt (Json Web Token).

Premise of use

First, you need to introduce firebase/php-jwt into composer.json, and then you need to install composer.

Name explain
iss (issuer) Issuer, the requesting entity, can be the information of the user who initiated the request or the issuer of jwt
sub (Subject) Setting themes, similar to those used in email
aud (audience) Party receiving jwt
exp (expire) token expiration time
nbf (not before) The current time is not available until the nbf set time
iat (issued at) token creation time
jti (JWT ID) Set a unique token for the current token
class JWTTool extends Controller {

    public function __construct(ContainerInterface $container = null)
    {
        header("Content-Type: text/html; charset=utf-8");
        $this->setContainer($container);
    }


    private $key = 'yayuanzi';//secret key
    private $iss = "http://example.org/send"; //issuer
    private $aud = "http://example.org/accept;//recipient

    /**
     * @param $data Encrypted data
     * @param int $is_exp Whether to add valid time or not
     * @param int $time  Effective duration
     * @return string
     */
    public function generateToken($data,$is_exp = 1,$time = 86400){
        $token['iss'] = $this->iss;
        $token['aud'] = $this->aud;
        $token['iat'] = strtotime(date('Y-m-d H:i:s'));
              if($is_exp){
            $token['exp'] = strtotime(date('Y-m-d H:i:s'))+$time;
        }
        $token['data'] = $data;
        $jwt = JWT::encode($token, $this->key);//alg, default HS256 mode
        return $jwt;
    }

    /**
     * Verification
     * @param $jwt
     * @param $client Platform number
     * @return array|\Symfony\Component\HttpFoundation\Response
     */
    public function verificationToken($jwt,$client)
    {
        $key = $this->key; //The key should be the same as when it was issued.
        try {
            JWT::$timestamp = strtotime(date('Y-m-d H:i:s'));//current time
            $decoded = JWT::decode($jwt, $key, ['HS256']); //HS256 mode, here and when the corresponding issuance

            if(empty($decoded->data)){
                throw new Exception('Not logged in');
            }

            if(empty($decoded->data->client)){
                throw new Exception('Illegal operation,Port error');
            }

            if($decoded->data->client != $client){
                throw new Exception('Illegal operation,Port error');
            }

            return Responses::arrays(
                'Login successfully',
                0,
                ['user_id'=>$decoded->data->user_id]
            );
        } catch(\Firebase\JWT\SignatureInvalidException $e) {  //Incorrect signature
            return Responses::arrays('Signature error',1);
        }catch(\Firebase\JWT\BeforeValidException $e) {  //
            return Responses::arrays($e->getMessage(),1);
        }catch(\Firebase\JWT\ExpiredException $e) {  // token expired
            return Responses::arrays('Invalidation of login credentials',-1);
        }catch(Exception $e) {  //Other mistakes
            return Responses::arrays($e->getMessage());
        }
    }

    public function verificationOther($jwt,$data)
    {
        $key = $this->key; //The key should be the same as when it was issued.
        try {
            JWT::$timestamp = strtotime(date('Y-m-d H:i:s'));//current time
            $decoded = JWT::decode($jwt, $key, ['HS256']); //HS256 mode, here and when the corresponding issuance

            $tag_data = (array)$decoded->data;
            foreach ($data as $k=>$v){
                if(!array_key_exists($k,$tag_data)){
                    throw new Exception('Validation failed');
                }
                if($tag_data[$k] != $data[$k]){
                    throw new Exception('Validation failed');
                }
            }
            return Responses::arrays(
                'Verify success',
                0,
                $data
            );
        } catch(\Firebase\JWT\SignatureInvalidException $e) {  //Incorrect signature
            return Responses::arrays('Signature error');
        }catch(\Firebase\JWT\BeforeValidException $e) {  //
            return Responses::arrays($e->getMessage());
        }catch(\Firebase\JWT\ExpiredException $e) {  // token expired
            return Responses::arrays('Voucher failure',1);
        }catch(Exception $e) {  //Other mistakes
            return Responses::arrays($e->getMessage());
        }
    }

}

 

Posted by jaslife on Sun, 06 Oct 2019 16:03:31 -0700