当前位置: 首页>>代码示例>>PHP>>正文


PHP JWT::leeway方法代码示例

本文整理汇总了PHP中Firebase\JWT\JWT::leeway方法的典型用法代码示例。如果您正苦于以下问题:PHP JWT::leeway方法的具体用法?PHP JWT::leeway怎么用?PHP JWT::leeway使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Firebase\JWT\JWT的用法示例。


在下文中一共展示了JWT::leeway方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: ValidateToken

 function ValidateToken()
 {
     try {
         $headers = getallheaders();
         if (!isset($headers['Authorization'])) {
             return;
         }
         $tokenObject = explode(' ', $headers['Authorization']);
         if (count($tokenObject) != 2) {
             return;
         }
         $tokenValue = $tokenObject[1];
         if ($tokenValue == NULL || $tokenValue == '') {
             return;
         }
         JWT::$leeway = 60 * 60 * 24;
         //24 hours
         $decoded = JWT::decode($tokenValue, "JWT_KEY", array('HS256'));
         if (empty($decoded)) {
             return;
         }
         $decoded_array = (array) $decoded;
         if (empty($decoded_array)) {
             return;
         }
         self::$token = $tokenValue;
         self::$userId = $decoded_array['uid'];
         self::$isAuthorized = TRUE;
     } catch (UnexpectedValueException $e) {
         return;
     } catch (Exception $e) {
         return;
     }
 }
开发者ID:vitalsaude,项目名称:api,代码行数:34,代码来源:JWT_Controller.php

示例2: getJwt

 public function getJwt()
 {
     $return = [];
     $key = "352352345623463246trswrgsdfgsdfgsdfgsert";
     $token = array("iss" => "http://example.org", "aud" => "http://example.com", "iat" => time(), "nbf" => time() - 4123123);
     /**
      * IMPORTANT:
      * You must specify supported algorithms for your application. See
      * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
      * for a list of spec-compliant algorithms.
      */
     $jwt = JWT::encode($token, $key);
     $return[] = $jwt;
     $decoded = JWT::decode($jwt, $key, array('HS256'));
     $return[] = $decoded;
     /*
      NOTE: This will now be an object instead of an associative array. To get
      an associative array, you will need to cast it as such:
     */
     $decoded_array = (array) $decoded;
     $return[] = $decoded_array;
     /**
      * You can add a leeway to account for when there is a clock skew times between
      * the signing and verifying servers. It is recommended that this leeway should
      * not be bigger than a few minutes.
      *
      * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
      */
     JWT::$leeway = 60;
     // $leeway in seconds
     $decoded = JWT::decode($jwt, $key, array('HS256'));
     $return[] = $decoded;
     return $return;
 }
开发者ID:vihoangson,项目名称:Family,代码行数:34,代码来源:JwtLib.php

示例3: verifyToken

 public function verifyToken()
 {
     $token = null;
     $headers = apache_request_headers();
     /*
      * Look for the 'authorization' header
      */
     $authHeader = $headers['authorization'];
     if ($this->debug) {
         $this->utils->debug(__METHOD__, $authHeader);
     }
     if ($authHeader) {
         //$matches = array();
         //preg_match('/Token token="(.*)"/', $headers['Authorization'], $matches);
         //if(isset($matches[1])){
         //  $token = $matches[1];
         //}
         /*
          * Extract the jwt from the Bearer
          */
         //$jwt = sscanf($authHeader, 'Authorization: Bearer %s');
         $jwt = str_replace('Bearer ', '', $authHeader);
         if ($jwt) {
             /*
              * decode the jwt using the key from config
              */
             $privateKey = $this->utils->readFile('private/apikey');
             $secretKey = base64_decode($privateKey);
             JWT::$leeway = 5;
             $token = JWT::decode($jwt, $secretKey, array('HS512'));
             return $token;
         } else {
             /*
              * No token was able to be extracted from the authorization header
              */
             //header('HTTP/1.0 400 Bad Request');
             throw new Exception('Token was not able to be extracted from the authorization header');
             return false;
         }
     } else {
         /*
          * The request lacks the authorization token
          */
         //header('HTTP/1.0 400 Bad Request');
         throw new Exception('Token not found in request');
         return false;
     }
 }
开发者ID:bandjam,项目名称:site-base,代码行数:48,代码来源:AuthController.php

示例4: isTokenValid

/**
* @name isTokenValid
* @description
* Helps in decoding the Token. If it's valid, returns the decoded_array. Otherwise, returns null
*/
function isTokenValid($tokenFromClient)
{
    try {
        // decode the jwt
        $secretKey = base64_decode(SECRET_KEY);
        JWT::$leeway = 60;
        // decode the key
        $token = JWT::decode($tokenFromClient, $secretKey, array('HS256'));
        // if no exception twron here, we are good to go.
        // let's also decode so we can access some info about the user.
        $decoded_array = (array) $token;
        // return
        return $decoded_array;
    } catch (Exception $e) {
        return NULL;
    }
}
开发者ID:healthy380,项目名称:Angular-php-login-demo,代码行数:22,代码来源:index.php

示例5: tokenVerify

 /**
  * Decodes the JSON Web Token received as a request header.
  *
  * @param string $authHeader Bearer <token string>
  * @return array The decoded payload of the JWT
  */
 public static function tokenVerify($authHeader)
 {
     $tokenDecoded_array = [];
     if ($authHeader) {
         $jwt = substr($authHeader, 7);
         if ($jwt) {
             try {
                 JWT::$leeway = 60;
                 $tokenDecoded = JWT::decode($jwt, $GLOBALS['key'], array('HS256'));
                 $tokenDecoded_array = (array) $tokenDecoded;
             } catch (\Exception $e) {
                 echo "Unauthorized! " . $e->getMessage();
             }
         }
     } else {
         echo json_encode(array('status' => 'Bad request', 'message' => "No token from Authorization header!"));
     }
     return $tokenDecoded_array;
 }
开发者ID:andela-sachungo,项目名称:php-checkpoints,代码行数:25,代码来源:Reusable.php

示例6: beforeFilter

 public function beforeFilter()
 {
     parent::beforeFilter();
     $this->layout = 'ajax';
     JWT::$leeway = 5;
     // $leeway in seconds
     try {
         $token = JWT::decode($this->request->header('Server-Token'), Configure::read('Autobahn.key'), array('HS256'));
     } catch (Exception $e) {
         throw new ForbiddenException('Could not auth your request');
     }
     $this->loadModel('User');
     if (!isset($token->userId) || !$this->User->exists($token->userId)) {
         throw new ForbiddenException('Could not auth your request or user does not exists');
     }
     $this->currUserID = $token->userId;
     $this->currUser = $this->User->findById($token->userId);
     $this->Auth->login($this->currUser['User']);
     if ($this->Auth->loggedIn()) {
         $this->_initTimezone($this->currUser['User']['timezone']);
         $this->_initLang($this->currUser['User']['lang']);
         $this->Auth->allow('*');
     }
 }
开发者ID:nilBora,项目名称:konstruktor,代码行数:24,代码来源:MyTimeAppController.php

示例7: __construct

 /**
  * @param int $leeway for checking timestamps
  */
 public function __construct($leeway = null)
 {
     $leeway = $leeway ?: getenv('JWT_LEEWAY');
     JWT::$leeway = $leeway ?: 0;
 }
开发者ID:generationtux,项目名称:jwt-artisan,代码行数:8,代码来源:FirebaseDriver.php

示例8: __construct

 /**
  * Constructor
  * @param string $secretKey injected kernel secret key
  */
 public function __construct($secretKey)
 {
     $this->jwtKey = self::PREPEND_KEY . $secretKey;
     JWT::$leeway = 5;
 }
开发者ID:stopfstedt,项目名称:ilios,代码行数:9,代码来源:JsonWebTokenManager.php

示例9: __construct

 /**
  * JwtService constructor
  *
  * @param ClaimManagerContract $claimManager
  */
 public function __construct(ClaimManagerContract $claimManager)
 {
     $this->key = Config::get('jwt.secret');
     $this->claimManager = $claimManager;
     JWT::$leeway = Config::get('jwt.leeway');
 }
开发者ID:wisoot,项目名称:jwt-guard,代码行数:11,代码来源:JwtService.php

示例10: show

 public function show()
 {
     $Model = new Model();
     $authority = M('authority');
     //  $USER->where('ID=201522040840')->select();
     $list = $authority->select();
     // echo M("authority")->getLastSql();
     //   $this->assign('list',$list);
     // $list=array('total'=>100,'row'=>$list);
     $token = json_encode($list);
     //json
     print_r($token);
     // $arr=json_decode($jlist);
     // echo '使用输出'.$arr->row[0]->id;
     //    print_r($list[0]);
     //$arr[0]=$list[0];
     //  echo $list[0]['id'];
     /*  echo 'daole';
         $id=201522040840;
         $sql="select name from __PREFIX__user where id=$id";
         $res=mysql_query($sql);
         $res=$Model->query($sql);
         $Model = new Model()  */
     // 实例化一个model对象 没有对应任何数据表
     //$Model->query("select * from __PREFIX__user where status=1");
     // 3.2.2版本以上还可以直接使用
     // $Model->query("select * from __USER__ where status=1");
     //json数组
     /*  $token = array(
          "iss" => "http://example.org",
          "aud" => "http://example.com",
          "iat" => 1356999524,
          "nbf" => 1357000000
         ); */
     /**
      * IMPORTANT:
      * You must specify supported algorithms for your application. See
      * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
      * for a list of spec-compliant algorithms.
      */
     $key = "example_key";
     $jwt = JWT::encode($token, $key);
     print_r($jwt);
     echo '<br>';
     $decoded = JWT::decode($jwt, $key, array('HS256'));
     //json
     print_r($decoded);
     $arr = json_decode($decoded);
     //php数组
     print_r($decoded->iss);
     echo '<br>';
     echo $arr->iss;
     echo '<br>';
     /*
     NOTE: This will now be an object instead of an associative array. To get
     an associative array, you will need to cast it as such:
     */
     $decoded_array = (array) $decoded;
     /**
      * You can add a leeway to account for when there is a clock skew times between
      * the signing and verifying servers. It is recommended that this leeway should
      * not be bigger than a few minutes.
      *
      * Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
      */
     JWT::$leeway = 60;
     // $leeway in seconds
     $decoded = JWT::decode($jwt, $key, array('HS256'));
     // $decoded[0]->id;
     /*   $Model=new Model();
           echo 'daole';
           $id=201522040840;
           $sql="select name from __PREFIX__user where id=$id";
           // $res=mysql_query($sql);
          $res=$Model->query($sql); */
     /*  $Model = new Model() // 实例化一个model对象 没有对应任何数据表
          //$Model->query("select * from __PREFIX__user where status=1");
          // 3.2.2版本以上还可以直接使用
          $Model->query("select * from __USER__ where status=1");
         */
     print_r($res);
     /*        $authority = M('authority');
                //  $USER->where('ID=201522040840')->select();
                $list = $authority->select();
                // echo M("authority")->getLastSql();
                //   $this->assign('list',$list);
                // $list=array('total'=>100,'row'=>$list);
                $jlist=json_encode($list);
                // $arr=json_decode($jlist);
                // echo '使用输出'.$arr->row[0]->id;
                //    print_r($list[0]);
                //$arr[0]=$list[0];
                //  echo $list[0]['id'];
                for($i=0;$i<=2;$i++){
                //  echo '='.$list[$i]['id'].';name='.$list[$i]['name'].'<br>';
                $arr[$i]=array(
                '学号'=>$list[$i]['id'],
                '姓名'=>$list[$i]['id']);
                }
               print_r( json_encode($arr)); */
//.........这里部分代码省略.........
开发者ID:ivyhappy,项目名称:PHYMAN,代码行数:101,代码来源:TestfunctionController.class.php

示例11: init

 public function init()
 {
     parent::init();
     JWT::$leeway = $this->leeway;
     self::$_instance = $this;
 }
开发者ID:fproject,项目名称:yii2-authclient,代码行数:6,代码来源:OAuth2.php

示例12: getMatchers

 public function getMatchers()
 {
     return ['beValidJWSToken' => function ($token) {
         /*
          * Ensure the token is:
          *  - a string
          *  - that can be decoded as a JWT,
          *  - validates against the API key
          *  - and contains the expected claims.
          */
         // Token must be a string.
         if (!is_string($token)) {
             throw new FailureException(sprintf('Token must be a string. ' . gettype($token) . ' found.'));
         }
         //---
         try {
             JWT::$leeway = 5;
             // $leeway in seconds
             $decoded = JWT::decode($token, self::API_KEY, array('HS256'));
         } catch (SignatureInvalidException $e) {
             throw new FailureException($e->getMessage());
         }
         //---
         // iss must match our service id.
         if ($decoded->iss !== self::SERVICE_ID) {
             throw new FailureException(sprintf(sprintf("Unable to validate iss claim. '%s' expected, but '%s' found.", $decoded->iss, self::SERVICE_ID)));
         }
         //---
         $time = time();
         // iat must be a recent timestamp.
         if ($decoded->iat < $time - 10 || $decoded->iat > $time + 10) {
             throw new FailureException(sprintf(sprintf("Unable to validate iat claim. %d expected to be within ten seconds of %d.", $decoded->iat, $time)));
         }
         return true;
     }, 'beInvalidJWSToken' => function ($token) {
         /**
          * Returns true when the JWT throws a SignatureInvalidException.
          */
         try {
             JWT::$leeway = 5;
             // $leeway in seconds
             JWT::decode($token, self::API_KEY, array('HS256'));
         } catch (SignatureInvalidException $e) {
             return true;
         }
         throw new FailureException('Invalid token expected, but the one passed appears valid.');
     }];
 }
开发者ID:alphagov,项目名称:notifications-php-client,代码行数:48,代码来源:JsonWebTokenSpec.php

示例13: jwt

 protected function jwt($payload = array())
 {
     global $_JWTConf;
     //fmt
     $jwt = null;
     $jdata = array('iat' => $_JWTConf['issuedAt'], 'jti' => $_JWTConf['tokenId'], 'iss' => $_JWTConf['issuer'], 'nbf' => $_JWTConf['notBefore'], 'exp' => $_JWTConf['expire'], 'payload' => $payload);
     try {
         //set gracefully
         JWT::$leeway = JWT_LEEWAT_TS;
         //try to munge
         $jwt = JWT::encode($jdata, $_JWTConf['secretKey']);
         @header('X-WWW-Authenticate: Basic realm="Ldap-API Secured Area"');
         @header('X-Authorization: Bearer ' . $jwt);
         //remove
         JWT::$leeway = 0;
         debug("jwt() : [INFO] {$jwt};");
     } catch (\Firebase\JWT\BeforeValidException $e) {
         debug("jwt() : [BeforeValidException]" . $e->getMessage());
     } catch (\Firebase\JWT\ExpiredException $e) {
         debug("jwt() : [ExpiredException]" . $e->getMessage());
     } catch (\Firebase\JWT\SignatureInvalidException $e) {
         debug("jwt() : [SignatureInvalidException]" . $e->getMessage());
     } catch (Exception $e) {
         debug("jwt() : [Exception]" . $e->getMessage());
     }
     //give it back
     return $jwt;
 }
开发者ID:bayugyug,项目名称:mobile-web-service,代码行数:28,代码来源:class-ldap-api.php

示例14: decode

 /**
  * Decode jwt token string
  * @param string $token
  * @return object|bool
  * @throws Exception
  */
 public function decode($token)
 {
     JWT::$leeway = $this->leeway;
     try {
         $payload = JWT::decode($token, $this->key, [$this->algorithm]);
     } catch (Exception $e) {
         return false;
     }
     // ensure that iss, aud, and csrf are good
     $tokenDefaults = $this->getTokenDefaults();
     if ($payload->iss != $tokenDefaults["iss"] || $payload->aud != $tokenDefaults["aud"]) {
         return false;
     }
     if (!empty($payload->csrf) && !$this->request->validateCsrfToken($payload->csrf)) {
         return false;
     }
     return $payload;
 }
开发者ID:amnah,项目名称:yii2-angular,代码行数:24,代码来源:JwtAuth.php

示例15: testInvalidTokenWithIatLeeway

 public function testInvalidTokenWithIatLeeway()
 {
     JWT::$leeway = 60;
     $payload = array("message" => "abc", "iat" => time() + 65);
     // issued too far in future
     $encoded = JWT::encode($payload, 'my_key');
     $this->setExpectedException('Firebase\\JWT\\BeforeValidException');
     $decoded = JWT::decode($encoded, 'my_key', array('HS256'));
     JWT::$leeway = 0;
 }
开发者ID:furesoft,项目名称:php-jwt,代码行数:10,代码来源:JWTTest.php


注:本文中的Firebase\JWT\JWT::leeway方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。