You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Vonage PHP SDK生成JWT时遇到sub声明配置错误及用户无效问题

解决Vonage JWT生成时'sub'字段的冲突问题

我刚好遇到过类似的问题,这是因为Vonage的JWT构建器对标准注册声明(比如sub、exp这类)有专门的处理逻辑,不能直接和自定义声明一起放进generateJwt()的参数数组里。同时sub字段是Vonage验证用户身份的必需项,所以不能直接移除,得用正确的方式设置它。

问题根源

  • 当你把sub放进claims数组时,Vonage的JWT构建器会把它当成非注册自定义声明,但sub是JWT标准里的注册声明,所以触发了Builder#withClaim() is meant to be used for non-registered claims的错误。
  • 移除sub后,Vonage服务端找不到用户标识,自然会返回user:error:invalid-user的验证错误。

解决方案:使用JWT构建器的专用方法设置注册声明

你需要用Vonage Client提供的JWT构建器,通过链式调用专用方法来设置sub、exp这些注册声明,再添加自定义的acl声明。修改后的代码如下:

$keypair = new \Vonage\Client\Credentials\Keypair(file_get_contents(storage_path('voip/vonage/private.key')), env('NEXMO_APPLICATION_ID'));
$client = new \Vonage\Client($keypair);

// 创建JWT构建器实例
$jwtBuilder = $client->getJwtBuilder();

// 用专用方法设置注册声明
$jwtBuilder->withSubject('apg-cs')
           ->withExpiration(strtotime(date('Y-m-d', strtotime('+24 Hours'))));

// 添加自定义的ACL声明
$jwtBuilder->addClaim('acl', [
    'paths' => [
        '/*/users/**' => (object) [],
        '/*/conversations/**' => (object) [],
        '/*/sessions/**' => (object) [],
        '/*/devices/**' => (object) [],
        '/*/image/**' => (object) [],
        '/*/media/**' => (object) [],
        '/*/applications/**' => (object) [],
        '/*/push/**' => (object) [],
        '/*/knocking/**' => (object) [],
        '/*/legs/**' => (object) [],
    ]
]);

// 生成JWT并转为字符串
$token = $jwtBuilder->build();
return $token->toString();

关键修改点

  1. 用getJwtBuilder()获取构建器实例,替代直接传入claims数组给generateJwt()
  2. 注册声明使用专用方法:
    • withSubject() 设置sub字段
    • withExpiration() 设置exp字段
  3. 自定义声明(比如acl)用addClaim()方法添加

这样既符合Vonage JWT构建器的规范,又能满足服务端对sub字段的验证要求,应该就能正常生成可用的JWT了。

内容的提问来源于stack exchange,提问作者Jazz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:37:39