使用 JWT 创建令牌时遇到问题

问题描述 投票:0回答:2

我正在构建一个 API,但在使用 JWT 创建令牌时出现未捕获错误,当我运行 post man 调用时,我会进入错误日志堆栈跟踪:

#0 [internal function]: Api->generateToken()
#1 /home/example/public_html/Exampleapicall/rest.php(42): ReflectionMethod->invoke(Object(Api))
#2 /home/example/public_html/Exampleapicall/index.php(4): Rest->processApi()
#3 {main}
thrown in /home/example/public_html/Exampleapicall/api.php on line 36
[19-May-2018 02:04:47 UTC] PHP Fatal error:  Uncaught Error: Class 'JWT' not found in /home/example/public_html/Exampleapicall/api.php:36
Stack trace:
#0 [internal function]: Api->generateToken()
#1 /home/example/public_html/Exampleapicall/rest.php(42): ReflectionMethod->invoke(Object(Api))
#2 /home/example/public_html/Exampleapicall/index.php(4): Rest->processApi()
#3 {main}

但是当我检查 PHP 服务器上的 jwt 文件时,它包含 JWT 类。

**jwt.php**
带有 jwt 类屏幕截图的页面

然后我用来创建令牌的页面是

**api.php**

//SECRETE_KEY 是为 JWT 创建 pass 的常量

   <?php 
  class Api extends Rest {
    public $dbConn;  
      
     public function __construct(){
        parent::__construct();  
        $db = new DbConnect;
        $this->dbConn = $db->connect();
        
    }
    
    public function generateToken(){
        $client_id_key = $this->validateParameter('client_id_key', $this->param['client_id_key'], STRING);
        //$client_secret_key = $this->validateParameter('client_secret_key', $this->param['client_secret_key'], STRING);
        //client_secret_key should be commented out it is not used for validation for security purposes, only id key
        
        $stmt = $this->dbConn->prepare("SELECT * FROM `api_clients_properties` WHERE client_id = :client_id_key");
        $stmt->bindParam(":client_id_key", $client_id_key);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!is_array($user)){
            $this->returnResponse(API_NAME_REQUIRED, "Invalid Client Id Key");
        }
        
        if ($user['property_status'] == "not verified"){
           $this->returnResponse(API_NAME_REQUIRED, "Property not verified, please contact admin, to verify it");   
        }
            
        $payload = [
           'iat' => time(),
           'iss' => 'localhost',
           'exp' => time() + (60),
           'userId' => $user['id']
        ];
        $token = JWT::encode($payload, SECRETE_KEY);
        echo $token;
    }
     
  }

?>
php api jwt token
2个回答
2
投票

JWT
类位于命名空间
Firebase\JWT
中,因此您需要
use
它:

use \Firebase\Jwt\Jwt;
Jwt::encode(...);

或者在调用时使用其完整的命名空间:

\Firebase\Jwt\Jwt::encode();

0
投票

如果您从 GitHub 复制文件而不是使用 Composer 来安装它,则需要注释掉文件顶部的命名空间行。因此,从我在

jwt.php
屏幕截图第一行最顶部的快照中,您将注释掉
//namespace Firebase\JWT;
,并且您不会再次收到 500 内部服务器错误。

© www.soinside.com 2019 - 2024. All rights reserved.