我正在使用Firebase的php-jwt库在我的应用程序中实现JWT。我在网站上尝试了这个例子,它运行正常。
$token = array(
"iss" => "http://example.org",
"aud" => "http://example.com",
"iat" => 1356999524,
"nbf" => 1357000000
);
但是,如果我尝试包含其他声明(例如exp或sub),则会抛出UnexpectedValueException(“错误的段数”)异常。有人遇到过这个问题吗? php-jwt库是否仅支持示例中显示的四个声明?在api中接收令牌的代码如下:
$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;
如果使用站点中的示例生成令牌,那么它可以正常工作。如果使用以下声明生成令牌:
$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
);
然后api调用失败。
从app开始,令牌发送如下:
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());
}
由于