CakePHP身份验证插件返回空标识对象

时间:2018-03-28 11:45:42

标签: authentication cakephp jwt cakephp-3.0

我使用CakePHP 3.5.14和which is the default model for the ORM resolver v1.0.0-rc4使用JWT身份验证。身份验证本身(生成和评估令牌)有效,但尝试获取令牌持有者的身份会返回一个空对象。 我设置并运行了User模型(example),users表没有什么特别之处,它有通常的列idusernamepasswordemail。作曲家要求cakephp/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;

1 个答案:

答案 0 :(得分:2)

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

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

如果要访问检索到的数据,ORM解析器应该是一个实体(注意合同定义了\ArrayAccess|array,所以一定要实现检查,如果你期望一个实体),然后调用\Authentication\IdentityInterface::getOriginalData()

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

另见