Home » Php » Non supported claims in JWT implementation

Non supported claims in JWT implementation

Posted by: admin June 30, 2018 Leave a comment

Questions:

I am implementing JWT in my application using php-jwt library from Firebase. I tried the example in the site and it is working fine.

$token = array(
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => 1356999524,
"nbf" => 1357000000
);

However if I try to include other claims such as exp or sub, it throws UnexpectedValueException (‘Wrong number of segments’) exception. Has somebody encountered this issue ? Does the php-jwt library supports only the four claims shown in the example ? The code to receive the token in api is given below:

$headers = null;
if (isset($_SERVER['Authorization'])) {
$headers = trim($_SERVER["Authorization"]);
}
else if (isset($_SERVER['HTTP_AUTHORIZATION'])) { 
$headers = trim($_SERVER["HTTP_AUTHORIZATION"]);
} elseif (function_exists('apache_request_headers')) {
$requestHeaders = apache_request_headers();

$requestHeaders = array_combine(array_map('ucwords', array_keys($requestHeaders)), array_values($requestHeaders));
//print_r($requestHeaders);
if (isset($requestHeaders['Authorization'])) {
    $headers = trim($requestHeaders['Authorization']);
    }
  }
 if (!empty($headers)) {
    if (preg_match('/Bearer\s(\S+)/', $headers, $matches)) {
        $jwt = $matches[1];
    }
}

$key = "example_key";
$decoded = JWT::decode($jwt, $key, array('HS256'));
$decoded_array = (array) $decoded;

If the token is generated using the example in the site, then it works fine. If the token is generated using claims like:

$tokenId    = base64_encode(mcrypt_create_iv(32));
$issuedAt   = time();
$notBefore  = $issuedAt + 3;             
$expire     = $notBefore + 3600;           

$token = array(
    "iss" => "http://example.com",
    "aud" => "http://example.com",
    "iat" => $issuedAt,
    "nbf" => $notBefore,
    "exp"    => $expire,
    "gate" => "kanchanjuri",
    "tokenId" => $tokenId
);

then the api call fails.

From app, the token is sent s follows:

      HttpURLConnection con = null;
      URL url = new URL(query);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.addRequestProperty("Authorization", "Bearer " + token);
            if (con.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP error code : "
                        + con.getResponseCode());
            }

Thanks

Answers: