I’m trying to use JWT library from Firebase in PHP. This is my code:
$env = parse_ini_file('.env');
class Auth {
private $service;
public function __construct($service) {
$this->service = $service;
}
public function login($user, $password) {
global $env;
if ($user != $env['user'] || $password != $env['password']) {
return null;
}
$date = new DateTimeImmutable();
$expire_at = $date->modify('+6 minutes')->getTimestamp();
$payload = [
'iat' => $date->getTimestamp(),
'iss' => $env['domain'],
'nbf' => $date->getTimestamp(),
'exp' => $expire_at,
'userName' => $user,
];
return JWT::encode(
$payload,
$env['secret'],
'HS512'
);
}
private function valid_token($jwt) {
global $env;
$token = JWT::decode($jwt, $env['secret'], ['HS512']);
$now = new DateTimeImmutable();
return $token->iss == $env['domain'] &&
$token->nbf > $now->getTimestamp() &&
$token->exp > $now->getTimestamp();
}
public function __call($method, $params) {
$jwt = array_shift($params);
if (!$this->valid_token($jwt)) {
throw new Exception("Invalid Token");
}
if (!in_array($method, $methods)) {
throw new Exception("Invalid method $method");
}
return call_user_func_array(array($this->service, $method), $params);
}
}
But when I try to decode the JWT I got this exception:
Fatal error: Uncaught Error: FirebaseJWTJWT::decode(): Argument #3 ($headers) cannot be passed by reference in /home/kuba/projects/jcubic/terminal/jwt/service.php:45 Stack trace: #0 /home/kuba/projects/jcubic/terminal/jwt/service.php(54): Auth->valid_token() #1 /home/kuba/projects/jcubic/terminal/jwt/json-rpc.php(302): Auth->__call() #2 /home/kuba/projects/jcubic/terminal/jwt/service.php(73): handle_json_rpc() #3 {main} thrown in /home/kuba/projects/jcubic/terminal/jwt/service.php on line 45
ChatGPT 3.5 suggested to change ['HS512']
into array(HS512')
which throw the same error.
The code is based on this article: How to Secure a PHP API Using JWT.
To give you a bit of background I’m trying to use this Auth class as a wrapper for Service object and it all act as JSON-RPC for jQuery Terminal. That out of the box call login function get the token save it in localStorage and pass it to other methods as first argument.
2
Answers
The article I was reading have probably the old API that changed.
The proper code look like this:
it can be found in README for the project.
Downgrade to the previous version.
They’ve changed header behavior in version 6.6.0 (2023-06-13)