示例#1
1
 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;
     }
 }
示例#2
0
 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;
 }
示例#3
0
 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;
     }
 }
/**
* @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;
    }
}
 /**
  * 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;
 }
 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('*');
     }
 }
 /**
  * @param int $leeway for checking timestamps
  */
 public function __construct($leeway = null)
 {
     $leeway = $leeway ?: getenv('JWT_LEEWAY');
     JWT::$leeway = $leeway ?: 0;
 }
示例#8
0
 /**
  * Constructor
  * @param string $secretKey injected kernel secret key
  */
 public function __construct($secretKey)
 {
     $this->jwtKey = self::PREPEND_KEY . $secretKey;
     JWT::$leeway = 5;
 }
示例#9
0
 /**
  * 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');
 }
 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)); */
     /* for ($i=1; $i<=10; $i++) {
         jlist[i].id;
        
        } */
     // dump ($list->row[1]);
     //  $this->display();
     //header("Content-Type:text/html; charset=utf-8");
     /*   $Dao = M("authority"); // 实例化模型类
          // 构建写入的数据数组
          $data["id"] = "4";
          $data["name"] = "测试";//md5("123456");
          // 写入数据
          if($lastInsId = $Dao->add($data)){
          echo "插入数据 id 为:$lastInsId";
          } else {
          $this->error('数据写入错误!');
          } */
 }
示例#11
0
 public function init()
 {
     parent::init();
     JWT::$leeway = $this->leeway;
     self::$_instance = $this;
 }
 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.');
     }];
 }
 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;
 }
示例#14
0
 /**
  * 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;
 }
示例#15
0
 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;
 }
示例#16
0
<?php

require_once __DIR__ . '/../vendor/autoload.php';
use Firebase\JWT\JWT;
$key = "example_key";
$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.
 */
$jwt = JWT::encode($token, $key);
$decoded = JWT::decode($jwt, $key, array('HS256'));
print_r($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;
/**
 * 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'));
示例#17
0
 public static function RequestAreAuthorized($returnUserId = false)
 {
     $request = new Request();
     $authHeader = $request->getHeader('authorization');
     if ($authHeader) {
         list($jwt) = sscanf($authHeader->toString(), 'Authorization: Bearer %s');
         if ($jwt) {
             try {
                 $secretKey = "CoppinPannequinAudio";
                 JWT::$leeway = 5;
                 $token = JWT::decode($jwt, $secretKey, array('HS512'));
                 if ($returnUserId) {
                     return $token->data->userId;
                 }
                 return true;
             } catch (Exception $e) {
                 return false;
             }
             return false;
         }
         return false;
     }
     return false;
 }
示例#18
0
文件: jwt.php 项目: bayugyug/LDAP-Api
try {
    @session_start();
    //set gracefully
    JWT::$leeway = JWT_LEEWAT_TS;
    //try to munge
    $jwt = JWT::encode($xdata, $_JWTConf['secretKey']);
    $str = JWT::decode($jwt, $_JWTConf['secretKey'], array('HS256'));
    $_SESSION['_JWT'] = $jwt;
    @header('Content-type: application/json');
    @header('X-WWW-Authenticate: Basic realm="Ldap-API Secured Area"');
    @header('X-Authorization: Bearer ' . $jwt);
    echo '<hr><pre>JSON-JWT-ENCDODE:' . @var_export($jwt, 1) . '</pre><hr><hr><br>';
    echo '<hr><pre>JSON-JWT-DECODED:' . @var_export($str, 1) . '</pre><hr><hr><br>';
    echo '<hr><pre>JSON-JWT-payload:' . @var_export($str->payload, 1) . '</pre><hr><hr><br>';
    //remove
    JWT::$leeway = 0;
} catch (\Firebase\JWT\BeforeValidException $e) {
    echo '<br>Caught BeforeValidException: ', $e->getMessage(), "<br>";
    echo '<br>Caught BeforeValidException: ', $e->getCode(), "<br>";
} catch (\Firebase\JWT\ExpiredException $e) {
    echo '<br>Caught ExpiredException: ', $e->getMessage(), "<br>";
    echo '<br>Caught ExpiredException: ', $e->getCode(), "<br>";
} catch (\Firebase\JWT\SignatureInvalidException $e) {
    echo '<br>Caught SignatureInvalidException: ', $e->getMessage(), "<br>";
    echo '<br>Caught SignatureInvalidException: ', $e->getCode(), "<br>";
} catch (Exception $e) {
    echo '<br>Caught exception: ', $e->getMessage(), "<br>";
    echo '<br>Caught exception: ', $e->getCode(), "<br>";
}
$dmp = @var_export(apache_response_headers(), 1);
echo "dmp:<pre> {$dmp} </pre><br />\n";