'jwt decode throws Invalid argument supplied for foreach() on php-jwt and codeignitor 4
I have encoded a token with JWT::encode($payload, $key, 'HS256');
When I am trying to decode it with the same key, it throws an error.
Here is the code:
<?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)
{
//
}
}
So this happens every time when I try to decode, but works fine when I encode it.
Solution 1:[1]
After spending hours, I went through official documentation (https://github.com/firebase/php-jwt#readme), seems I had to use
JWT::decode($token, new Key($key, 'HS256'));
instead of JWT::decode($token, $key, ['HS256']);
Solution 2:[2]
It works for me like this:
use Firebase\JWT\Key; // add the library
JWT::decode($token, new Key($key, 'HS256'));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | hotheadhacker |
Solution 2 | richardec |