UnexpectedValueException: Incorrect key for this algorithm in JWT.php: 130
varun7952 opened this issue · 2 comments
varun7952 commented
I am trying my hand on this library to secure our APIs but on simple testing of JWT i am getting this error
Fatal error: Uncaught UnexpectedValueException: Incorrect key for this algorithm in /home/bitnami/vendor/firebase/php-jwt/src/JWT.php: 130
Stack trace:
#0 /opt/bitnami/apache/htdocs/test0023.php(33): Firebase\JWT\JWT: :decode()
#1 /opt/bitnami/apache/htdocs/test0023.php(16): checkJWT()
#2 {main
}
thrown in /home/bitnami/vendor/firebase/php-jwt/src/JWT.php on line 130
JWT decode/encode
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'on');
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
require_once ("/home/bitnami/vendor/autoload.php");
$action = $_POST['action'];
$phone = $_POST['phone'];
$token = $_POST['token'];
if($action == 'check'){
// Check
if(checkJWT($phone,$token)){
echo "Token Is Valid";
}else{
echo "Token In Not Valid";
}
echo $genToken;
}else{
// Generate
$genToken = generateJWT($phone);
echo $genToken;
}
function checkJWT($phone,$jwt) {
//print_r($phone.' '.$jwt);
$secret_Key = '1bjntGOwlg5Tnkamk08qgJkJZGDi8B6bzPU3x6Ic8fb7jKOsKGeGHXjkLHTMGD4';
//$token = JWT::decode($jwt, $secret_Key, array_keys(JWT::"HS256"));
$token = JWT::decode($jwt, new Key($secret_Key, 'HS256'));
//$token = JWT::decode($jwt, $secret_Key, array('HS256'));
$now = new DateTimeImmutable();
$domainName = 'example.com';
if ($token->iss !== $domainName || $token->nbf > $now->getTimestamp() || $token->exp < $now->getTimestamp()) {
header('HTTP/1.1 401 Unauthorized');
print_r('Not Valid');
return false;
}else{
print_r('Valid');
return true;
}
}
function generateJWT($phone) {
$secret_Key = '1bjntGOwlg5Tnkamk08qgJkJZGDi8B6bzPU3x6Ic8fb7jKOsKGeGHXjkLHTMGD4';
$date = new DateTimeImmutable();
$expire_at = $date->modify('+3 minutes')->getTimestamp(); // Add 60 seconds
$domainName = 'example.com';
$request_data = [
'iat' => $date->getTimestamp(), // Issued at: time when the token was generated
'iss' => $domainName, // Issuer
'nbf' => $date->getTimestamp(), // Not before
'exp' => $expire_at, // Expire
'userName' => $phone, // User name
];
$newToken = JWT::encode($request_data,$secret_Key,'HS512');
return $newToken;
}
?>
Krisell commented
You're using HS512
when generating the token and HS256
when verifying. You need to use the same algorithm.