【问题标题】:CakePHP authentication plugin returns empty identity objectCakePHP 身份验证插件返回空身份对象
【发布时间】:2026-01-15 15:05:01
【问题描述】:

我正在使用带有 JWT 身份验证的 CakePHP 3.5.14 和 official CakePHP authentication plugin v1.0.0-rc4。身份验证本身(生成和评估令牌)有效,但尝试获取令牌持有者的身份会返回一个空对象。 我有我的User 模型(which is the default model for the ORM resolver)设置并运行,users 表没有什么特别之处,它有通常的列idusernamepasswordemailcakephp/orm 已被作曲家要求。

这是 JWT 有效载荷的内容:

{
  "sub": 9,
  "aud": "http://example.com"
}

这是控制器功能的代码:

    $this->autoRender = false;
    $result = $this->Authentication->getResult();
    if ($result->isValid()) {  //evaluates true
        $user = $this->Authentication->getIdentity();
        $response = $user;
    } else {
        $response = array("error" => "You are not authorized.");
    }

    $json = json_encode($response);  //becomes {}
    $this->response->type('json');
    $this->response->body($json);
    return $this->response;

【问题讨论】:

    标签: authentication cakephp jwt cakephp-3.0


    【解决方案1】:

    一个空的 JSON 表示并不一定意味着对象是“空的”,而只是它的 JSON 表示是。

    最近围绕身份的 API 发生了很大变化,\Authentication\Controller\Component\AuthenticationComponent::getIdentity() 返回 \Authentication\IdentityInterface,它不包含 JSON 序列化功能,并且可用的 IdentityInterface 实现不将数据存储在公共属性中,因此它的 JSON表示将始终为空。

    如果你想访问检索到的数据,对于 ORM 解析器应该是一个实体(请注意,合约定义了 \ArrayAccess|array,所以如果你期望一个实体,请务必执行检查),然后调用 @987654326 @:

    $identity = $this->Authentication->getIdentity();
    $user = $identity->getOriginalData();
    

    另见

    【讨论】:

    • 请修复 Authentication Docs > The Identity Object 的链接
    最近更新 更多