ThinkPHP框架下使用php-jwt生成加密字符串保存用户基本信息替代session保存用户信息

转自 https://blog.csdn.net/bdl13588302605/article/details/81391003

1.JWT存放在ThinkPHP类库中的路径(截图所示即为需要用到的2个php文件)

2.JWT文件夹下的文件说明:

1).JWT.php  

功能①:根据用户基本信息、过期时间、秘钥生成时间等信息生成一个加密字符串(token)

功能②:根据客户端提交过来的加密字符串token,进行解码,验证用户信息真实性、token是否在有效期内,成功之后返回一个对象,包含用户基本信息、过期时间、秘钥等信息

文件内容:

<?php
vendor('phpJWT.Firebase.JWT.BlarDateTime');
 
/**
 * JSON Web Token implementation, based on this spec:
 * https://tools.ietf.org/html/rfc7519
 *
 * PHP version 5
 *
 * @category Authentication
 * @package  Authentication_JWT
 * @author   Neuman Vong <[email protected]>
 * @author   Anant Narayanan <[email protected]>
 * @license  http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
 * @link     https://github.com/firebase/php-jwt
 */
class JWT
{
 
    /**
     * When checking nbf, iat or expiration times,
     * we want to provide some extra leeway time to
     * account for clock skew.
     */
    public static $leeway = 0;
 
    /**
     * Allow the current timestamp to be specified.
     * Useful for fixing a value within unit testing.
     *
     * Will default to PHP time() value if null.
     */
    public static $timestamp = null;
    public static $supported_algs = array(
        'HS256' => array('hash_hmac', 'SHA256'),
        'HS512' => array('hash_hmac', 'SHA512'),
        'HS384' => array('hash_hmac', 'SHA384'),
        'RS256' => array('openssl', 'SHA256'),
        'RS384' => array('openssl', 'SHA384'),
        'RS512' => array('openssl', 'SHA512'),
    );
    
    /**
     * Decodes a JWT string into a PHP object.
     *
     * @param string        $jwt            The JWT
     * @param string|array  $key            The key, or map of keys.
     *                                      If the algorithm used is asymmetric, this is the public key
     * @param array         $allowed_algs   List of supported verification algorithms
     *                                      Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
     *
     * @return object The JWT's payload as a PHP object
     *
     * @throws UnexpectedValueException     Provided JWT was invalid
     * @throws SignatureInvalidException    Provided JWT was invalid because the signature verification failed
     * @throws BeforeValidException         Provided JWT is trying to be used before it's eligible as defined by 'nbf'
     * @throws BeforeValidException         Provided JWT is trying to be used before it's been created as defined by 'iat'
     * @throws ExpiredException             Provided JWT has since expired, as defined by the 'exp' claim
     *
     * @uses jsonDecode
     * @uses urlsafeB64Decode
     */
    public static function decode($jwt, $key, array $allowed_algs = array())
    {
        $bdtObj = new \BlarDateTime();
        $timestamp = is_null(static::$timestamp) ? time() : static::$timestamp;
 
        if (empty($key)) {
            logs('phpJWT | Firebase | JWT | JWT | decode | Key is empty');
            return false;
        }
        $tks = explode('.', $jwt);
        if (count($tks) != 3) {
            logs('phpJWT | Firebase | JWT | JWT | decode | Wrong number of segments');
            return false;
        }
        list($headb64, $bodyb64, $cryptob64) = $tks;
        if (null === ($header = static::jsonDecode(static::urlsafeB64Decode($headb64)))) {
            
            logs('phpJWT | Firebase | JWT | JWT | decode | Invalid header encoding');
            return false;
        }
        if (null === $payload = static::jsonDecode(static::urlsafeB64Decode($bodyb64))) {
            
            logs('phpJWT | Firebase | JWT | JWT | decode | Invalid claims encoding');
            return false;
        }
        if (false === ($sig = static::urlsafeB64Decode($cryptob64))) {
            
            logs('phpJWT | Firebase | JWT | JWT | decode | Invalid signature encoding');
            return false;
        }
        if (empty($header->alg)) {
            
            logs('phpJWT | Firebase | JWT | JWT | decode | Empty algorithm');
            return false;
        }
        if (empty(static::$supported_algs[$header->alg])) {
            
            logs('phpJWT | Firebase | JWT | JWT | decode | Algorithm not supported');
            return false;
        }
        if (!in_array($header->alg, $allowed_algs)) {
            
            logs('phpJWT | Firebase | JWT | JWT | decode | Algorithm not allowed');
            return false;
        }
        if (is_array($key) || $key instanceof \ArrayAccess) {
            if (isset($header->kid)) {
                if (!isset($key[$header->kid])) {
                    
                    logs('phpJWT | Firebase | JWT | JWT | decode | "kid" invalid, unable to lookup correct key');
                    return false;
                }
                $key = $key[$header->kid];
            } else {
                
                logs('phpJWT | Firebase | JWT | JWT | decode | "kid" empty, unable to lookup correct key');
                return false;
            }
        }
 
        // Check the signature
        if (!static::verify("$headb64.$bodyb64", $sig, $key, $header->alg)) {
            
            logs('phpJWT | Firebase | JWT | JWT | decode | Signature verification failed');
            return false;
        }
 
        // Check if the nbf if it is defined. This is the time that the
        // token can actually be used. If it's not yet that time, abort.
        if (isset($payload->nbf) && $payload->nbf > ($timestamp + static::$leeway)) {
            
            logs('phpJWT | Firebase | JWT | JWT | decode | Cannot handle token prior to '. date($bdtObj::ISO8601, $payload->nbf));
            return false;
        }
 
        // Check that this token has been created before 'now'. This prevents
        // using tokens that have been created for later use (and haven't
        // correctly used the nbf claim).
        if (isset($payload->iat) && $payload->iat > ($timestamp + static::$leeway)) {
            
            logs('phpJWT | Firebase | JWT | JWT | decode | Cannot handle token prior to ' . date($bdtObj::ISO8601, $payload->iat));
            return false;
        }
        // Check if this token has expired.
        if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
            
            logs('phpJWT | Firebase | JWT | JWT | decode | Expired token');
            return false;
        }
 
        return $payload;
    }
 
    /**
     * Converts and signs a PHP object or array into a JWT string.
     *
     * @param object|array  $payload    PHP object or array
     * @param string        $key        The secret key.
     *                                  If the algorithm used is asymmetric, this is the private key
     * @param string        $alg        The signing algorithm.
     *                                  Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
     * @param mixed         $keyId
     * @param array         $head       An array with header elements to attach
     *
     * @return string A signed JWT
     *
     * @uses jsonEncode
     * @uses urlsafeB64Encode
     */
    public static function encode($payload, $key, $alg = 'HS256', $keyId = null, $head = null)
    {
        $header = array('typ' => 'JWT', 'alg' => $alg);
        if ($keyId !== null) {
            $header['kid'] = $keyId;
        }
        if ( isset($head) && is_array($head) ) {
            $header = array_merge($head, $header);
        }
        $segments = array();
        $segments[] = static::urlsafeB64Encode(static::jsonEncode($header));
        $segments[] = static::urlsafeB64Encode(static::jsonEncode($payload));
        $signing_input = implode('.', $segments);
 
        $signature = static::sign($signing_input, $key, $alg);
        $segments[] = static::urlsafeB64Encode($signature);
        return implode('.', $segments);
    }
 
    /**
     * Sign a string with a given key and algorithm.
     *
     * @param string            $msg    The message to sign
     * @param string|resource   $key    The secret key
     * @param string            $alg    The signing algorithm.
     *                                  Supported algorithms are 'HS256', 'HS384', 'HS512' and 'RS256'
     *
     * @return string An encrypted message
     *
     * @throws DomainException Unsupported algorithm was specified
     */
    public static function sign($msg, $key, $alg = 'HS256')
    {
        if (empty(static::$supported_algs[$alg])) {
            logs('phpJWT | Firebase | JWT | JWT | sign | Algorithm not supported');
            return false;
        }
        list($function, $algorithm) = static::$supported_algs[$alg];
        switch($function) {
            case 'hash_hmac':
                return hash_hmac($algorithm, $msg, $key, true);
            case 'openssl':
                $signature = '';
                $success = openssl_sign($msg, $signature, $key, $algorithm);
                if (!$success) {
                    logs('phpJWT | Firebase | JWT | JWT | sign | OpenSSL unable to sign data');
                    return false;
                } else {
                    return $signature;
                }
        }
    }
 
    /**
     * Verify a signature with the message, key and method. Not all methods
     * are symmetric, so we must have a separate verify and sign method.
     *
     * @param string            $msg        The original message (header and body)
     * @param string            $signature  The original signature
     * @param string|resource   $key        For HS*, a string key works. for RS*, must be a resource of an openssl public key
     * @param string            $alg        The algorithm
     *
     * @return bool
     *
     * @throws DomainException Invalid Algorithm or OpenSSL failure
     */
    private static function verify($msg, $signature, $key, $alg)
    {
        if (empty(static::$supported_algs[$alg])) {
            throw new DomainException('Algorithm not supported');
        }
 
        list($function, $algorithm) = static::$supported_algs[$alg];
        switch($function) {
            case 'openssl':
                $success = openssl_verify($msg, $signature, $key, $algorithm);
                if ($success === 1) {
                    return true;
                } elseif ($success === 0) {
                    return false;
                }
                logs('phpJWT | Firebase | JWT | JWT | verify | OpenSSL error: '. openssl_error_string());
                return false;
                // returns 1 on success, 0 on failure, -1 on error.
            case 'hash_hmac':
            default:
                $hash = hash_hmac($algorithm, $msg, $key, true);
                if (function_exists('hash_equals')) {
                    return hash_equals($signature, $hash);
                }
                $len = min(static::safeStrlen($signature), static::safeStrlen($hash));
 
                $status = 0;
                for ($i = 0; $i < $len; $i++) {
                    $status |= (ord($signature[$i]) ^ ord($hash[$i]));
                }
                $status |= (static::safeStrlen($signature) ^ static::safeStrlen($hash));
 
                return ($status === 0);
        }
    }
 
    /**
     * Decode a JSON string into a PHP object.
     *
     * @param string $input JSON string
     *
     * @return object Object representation of JSON string
     *
     * @throws DomainException Provided string was invalid JSON
     */
    public static function jsonDecode($input)
    {
        if (version_compare(PHP_VERSION, '5.4.0', '>=') && !(defined('JSON_C_VERSION') && PHP_INT_SIZE > 4)) {
            /** In PHP >=5.4.0, json_decode() accepts an options parameter, that allows you
             * to specify that large ints (like Steam Transaction IDs) should be treated as
             * strings, rather than the PHP default behaviour of converting them to floats.
             */
            $obj = json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
        } else {
            /** Not all servers will support that, however, so for older versions we must
             * manually detect large ints in the JSON string and quote them (thus converting
             *them to strings) before decoding, hence the preg_replace() call.
             */
            $max_int_length = strlen((string) PHP_INT_MAX) - 1;
            $json_without_bigints = preg_replace('/:\s*(-?\d{'.$max_int_length.',})/', ': "$1"', $input);
            $obj = json_decode($json_without_bigints);
        }
 
        if (function_exists('json_last_error') && $errno = json_last_error()) {
            
            $error = static::handleJsonError($errno);
            logs('phpJWT | Firebase | JWT | JWT | jsonDecode | error '.$error);
            return null;
        } elseif ($obj === null && $input !== 'null') {
            logs('phpJWT | Firebase | JWT | JWT | jsonDecode | Null result with non-null input');
            return null;
        }
        return $obj;
    }
 
    /**
     * Encode a PHP object into a JSON string.
     *
     * @param object|array $input A PHP object or array
     *
     * @return string JSON representation of the PHP object or array
     *
     * @throws DomainException Provided object could not be encoded to valid JSON
     */
    public static function jsonEncode($input)
    {
        $json = json_encode($input);
        if (function_exists('json_last_error') && $errno = json_last_error()) {
            $error = static::handleJsonError($errno);
            logs('phpJWT | Firebase | JWT | JWT | jsonEncode | error '.$error);
            return false;
        } elseif ($json === 'null' && $input !== null) {
            
            logs('phpJWT | Firebase | JWT | JWT | jsonEncode | Null result with non-null input');
            return false;
        }
        return $json;
    }
 
    /**
     * Decode a string with URL-safe Base64.
     *
     * @param string $input A Base64 encoded string
     *
     * @return string A decoded string
     */
    public static function urlsafeB64Decode($input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $padlen = 4 - $remainder;
            $input .= str_repeat('=', $padlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }
 
    /**
     * Encode a string with URL-safe Base64.
     *
     * @param string $input The string you want encoded
     *
     * @return string The base64 encode of what you passed in
     */
    public static function urlsafeB64Encode($input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }
 
    /**
     * Helper method to create a JSON error.
     *
     * @param int $errno An error number from json_last_error()
     *
     * @return void
     */
    private static function handleJsonError($errno)
    {
        $messages = array(
            JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
            JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
            JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
            JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
            JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
        );
        
        return isset($messages[$errno]) ? $messages[$errno] : 'Unknown JSON error: ' . $errno;
    }
 
    /**
     * Get the number of bytes in cryptographic strings.
     *
     * @param string
     *
     * @return int
     */
    private static function safeStrlen($str)
    {
        if (function_exists('mb_strlen')) {
            return mb_strlen($str, '8bit');
        }
        return strlen($str);
    }
}

2).BlarDateTime.php

功能:继承:DateTime类,用于获取ISO8601格式的时间

文件内容:

<?php
class BlarDateTime extends DateTime {
 
    /**
     * Return Date in ISO8601 format
     *
     * @return String
     */
    public function getISO8601Time() {
        return $this->format('Y-m-d\TH:i:sO');
    }
}

3).生成加密字符串,设置有效期

    public function testCreateToken(){
    
        $payload['user_name'] = '张三';
        $payload['user_id'] = '1';
        $payload['expire_time'] = 60; //token有效期为60秒
        
        $ret = $this -> _createAPIToken($payload);
        
        echo $ret;
    }
    /**
     * 生成jwt token
     * @param array  $payload 用户信息
     * @param string $alg  加密类型
     * @return string
     */
    private function _createAPIToken($payload,$alg = 'HS256')
    {
 
        Vendor('phpJWT.Firebase.JWT.JWT');
        
        $jwtObj = new \JWT();
        
        $key = self::$Key; //key
        
        $payload['uid'] = $payload['user_id'];//(必填参数,值自定义)
        $payload['iat'] = $_SERVER['REQUEST_TIME'];//签发时间(必填参数)
        $payload['exp'] = $_SERVER['REQUEST_TIME'] + $payload['expire_time'];//过期时间(必填参数)
        $jwt = $jwtObj::encode($payload, $key ,$alg);
        return $jwt;
    }

生成的token(包含3部分,中间用’.‘号连接)示例如下:

eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX25hbWUiOiJcdTVmMjBcdTRlMDkiLCJ1c2VyX2lkIjoiMSIsImV4cGlyZV90aW1lIjo2MCwidWlkIjoiMSIsImlhdCI6MTUzMzI4ODIyNSwiZXhwIjoxNTMzMjg4Mjg1fQ.1cnxFqDzxjcEsw5eXAK1u4UbRrG5V8H0nc0vw3vgQpo

4).字符串解密

public function testCheckToken(){
    
        $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX25hbWUiOiJcdTVmMjBcdTRlMDkiLCJ1c2VyX2lkIjoiMSIsImV4cGlyZV90aW1lIjo2MCwidWlkIjoiMSIsImlhdCI6MTUzMzI4ODIyNSwiZXhwIjoxNTMzMjg4Mjg1fQ.1cnxFqDzxjcEsw5eXAK1u4UbRrG5V8H0nc0vw3vgQpo';// $_REQUEST['TOKEN'];
        
        $ret = $this -> _checkAPIToken($token);
        
        print_r($ret);
    }
    
    /**
     * 校验接口会话
     * @param string $ciphertext  jwt token
     * @param string $alg  解密类型
     * @return array/boolean
     */
    private function _checkAPIToken(&$ciphertext,$alg = array('HS256'))
    {
        Vendor('phpJWT.Firebase.JWT.JWT');
        
        $jwtObj = new \JWT();
        $key = self::$Key; //key
        $decoded = $jwtObj::decode($ciphertext, $key, $alg);
        
        if( !empty($decoded) ){ 
        
            $jwtRet = json_decode(json_encode($decoded),true);
            //此处是一个一维数组,包含加密前的所有信息,可以根据实际情况做验证,并返回验证通过后的用户信息
            //用户信息验证:省略
            return $jwtRet;
        }else{
            logs('Controller: Interfaces | _checkAPIToken | token out of time!');
            return false;
        }
        
    }

解密后的token(包含加密前的所有信息)

Array
(
    [user_name] => 张三
    [user_id] => 1
    [expire_time] => 60
    [uid] => 1
    [iat] => 1533288775
    [exp] => 1533288835
)

感谢作者大大的分享~~

猜你喜欢

转载自blog.csdn.net/bianb123/article/details/81662857
今日推荐