Your IP : 216.73.216.79


Current Path : /var/www/html/jkdm/common/components/
Upload File :
Current File : /var/www/html/jkdm/common/components/JWT.php

<?php

namespace common\components;
    
class JWT {
    const SECRET_KEY = 'OshIsABeautifulHumanBeing';
    
    private static $algorithms = ['HS256'=>'sha256','HS384'=>'sha384','HS512'=>'sha512'];
    private static $algorithm = 'HS256';
    private static $secret = 'secret';
    private static $leeway = 5; // seconds
    private static $ttl = 30; // seconds
    
    public static function getVerifiedClaims($token)
    {
        $time = time();
        $algorithms = static::$algorithms;
        $algorithm = static::$algorithm;
        $secret = static::$secret;
        $leeway = static::$leeway;
        $ttl = static::$ttl;
        
        if (!isset($algorithms[$algorithm])) return false;
        $hmac = $algorithms[$algorithm];
        $token = explode('.',$token);
        if (count($token)<3) return false;
        $header = json_decode(base64_decode(strtr($token[0],'-_','+/')),true);
        if (!$secret) return false;
        if ($header['typ']!='JWT') return false;
        if ($header['alg']!=$algorithm) return false;
        $signature = bin2hex(base64_decode(strtr($token[2],'-_','+/')));
        if ($signature!=hash_hmac($hmac,"$token[0].$token[1]",$secret)) return false;
        $claims = json_decode(base64_decode(strtr($token[1],'-_','+/')),true);
        if (!$claims) return false;
//        if (isset($claims['nbf']) && $time+$leeway<$claims['nbf']) return false;
//        if (isset($claims['iat']) && $time+$leeway<$claims['iat']) return false;
//        if (isset($claims['exp']) && $time-$leeway>$claims['exp']) return false;
//        if (isset($claims['iat']) && !isset($claims['exp'])) {
//            if ($time-$leeway>$claims['iat']+$ttl) return false;
//        }
        return $claims;
    }

    public static function generateToken($claims)
    {
        $time = time();
        $algorithms = static::$algorithms;
        $algorithm = static::$algorithm;
        $secret = static::$secret;
        $ttl = static::$ttl;
        
        $header = [];
        $header['typ']='JWT';
        $header['alg']=$algorithm;
        $token = [];
        $token[0] = rtrim(strtr(base64_encode(json_encode((object)$header)),'+/','-_'),'=');
        //$claims['iat'] = $time;
        //$claims['exp'] = $time + $ttl;
        $token[1] = rtrim(strtr(base64_encode(json_encode((object)$claims)),'+/','-_'),'=');
        if (!isset($algorithms[$algorithm])) return false;
        $hmac = $algorithms[$algorithm];
        $signature = hash_hmac($hmac, "$token[0].$token[1]", $secret, true);
        $token[2] = rtrim(strtr(base64_encode($signature),'+/','-_'),'=');
        return implode('.',$token);
    }
    
    
}