JWT令牌似乎正确,但收到的响应是401

时间:2019-01-10 23:13:53

标签: api oauth-2.0 jwt

我正在尝试使用JWT Bearer Grant Type连接到Docebo API并遇到问题:

使用下面的代码,我收到以下响应(即使我的$ token在https://jwt.io验证时似乎是正确的):

stdClass Object ( [name] => Unauthorized [message] => Array ( [0] => Your request was made with invalid credentials. ) [code] => 0 [status] => 401 )

以下是用于生成$ token的代码,以及该错误^

<?php 
ini_set('display_errors',1);
error_reporting(E_ALL);

function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

$key = 'example_public_key';

$headers = ['alg'=>'RS256','typ'=>'JWT'];
$headers_encoded = base64url_encode(json_encode($headers));

$today = time();
$tomorrow = time() + (1 * 24 * 60 * 60);
$payload = [
  'iss' => 'example_client_id',
  'sub' => 'example_user',
  'aud' => 'example.docebosaas.com',  
  'iat' => $today,
  'exp' => $tomorrow
];

$payload_encoded = base64url_encode(json_encode($payload));
$signature = hash_hmac('SHA256',"$headers_encoded.$payload_encoded",$key,true);
$signature_encoded = base64url_encode($signature);

$token = "$headers_encoded.$payload_encoded.$signature_encoded";

$curl = curl_init();
$curl_data =  array(
  'token' => $token
); 
curl_setopt_array($curl, array(
  CURLOPT_RETURNTRANSFER => 1,  
  CURLOPT_POSTFIELDS     => $curl_data, 
  CURLOPT_URL => 'https://example.docebosaas.com/manage/v1/user'
)); 
$resp = curl_exec($curl); 
curl_close($curl);

$json_obj = json_decode($resp);
print_r($json_obj);

更新:

根据下面的评论,我现在在其中添加了适当的标题,并且不再收到401。但是,将CURL调用更改为以下内容会出现新错误:

stdClass Object ( [error] => invalid_grant [error_description] => JWT failed signature verification )

这是更新的CURL调用的代码:

$curl = curl_init();
$curl_data =  array(
 'grant_type' => 'urn:ietf:params:oauth:grant-type:jwt-bearer',
 'scope' => 'api',
 'assertion' => $token
); 
curl_setopt_array($curl, array(
 CURLOPT_RETURNTRANSFER => 1,  
 CURLOPT_POSTFIELDS     => $curl_data, 
 CURLOPT_URL => 'https://example.docebosaas.com/oauth2/token'
)); 
$resp = curl_exec($curl); 
curl_close($curl);

$json_obj = json_decode($resp);
print_r($json_obj);

1 个答案:

答案 0 :(得分:1)

您的curl示例不包含我期望的标头,例如:

grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer
scope=api
assertion=YOUR_SIGNED_JWT

此外,您可能还想调用端点https://<yoursubdomain.docebosaas.com>/oauth2/token,以将签名的JWT转换为普通的承载令牌。然后,您可以使用标准的Authorization标头:

Authorization: Bearer YOUR_ACCESS_TOKEN

API General Information