jwt 解码在 codeigniter 4 中的 [=10th=]-jwt 上为 foreach() 提供的参数无效

jwt decode throws Invalid argument supplied for foreach() on php-jwt and codeignitor 4

我用 JWT::encode($payload, $key, 'HS256');

编码了一个令牌

当我试图用相同的密钥解码它时,它抛出一个错误。

代码如下:

<?php
 
namespace App\Filters;
 
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use \Firebase\JWT\JWT;
use Config\Services;
use Config\MyConfig;

 
class AuthFilter implements FilterInterface
{
  
    public function before(RequestInterface $request, $arguments = null)
    {
        $myconfig = new MyConfig;        

        $key = $myconfig->JWT_SECRET_KEY;
        
        $header = $request->getServer('HTTP_AUTHORIZATION');
        if(!$header) return Services::response()
                            ->setJSON(['msg' => 'Token Required'])
                            ->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
        $token = explode(' ', $header)[1];
 
        try {
            JWT::decode($token, $key, ['HS256']); // it throws error: jwt decode throws 
                                            // Invalid argument supplied for foreach()
        } catch (\Throwable $th) {
            return Services::response()
                            ->setJSON(['msg' => $th->getMessage()])
                            ->setStatusCode(ResponseInterface::HTTP_UNAUTHORIZED);
        }
    }
 
   
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        //
    }
}

所以每次我尝试解码时都会发生这种情况,但在我编码时工作正常。

花了几个小时后,我浏览了官方文档(https://github.com/firebase/php-jwt#readme),看来我不得不使用 JWT::decode($token, new Key($key, 'HS256')); 而不是 JWT::decode($token, $key, ['HS256']);

它对我来说是这样的:

use Firebase\JWT\Key;             // add the library

JWT::decode($token, new Key($key, 'HS256'));