Reputation: 182
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.
Upvotes: 1
Views: 1631
Reputation: 1
It works for me like this:
use Firebase\JWT\Key; // add the library
JWT::decode($token, new Key($key, 'HS256'));
Upvotes: 0
Reputation: 182
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']);
Upvotes: 4