身份对象

身份对象由身份验证服务返回,并在请求中可用。身份提供了一种方法 getIdentifier(),可以调用它来获取当前登录身份的主键值。

此对象存在的原因是提供一个接口,使其实现/来源

// Service
$authenticationService
    ->getIdentity()
    ->getIdentifier()

// Component
$this->Authentication
    ->getIdentity()
    ->getIdentifier();

// Request
$this->request
    ->getAttribute('identity')
    ->getIdentifier();

身份对象提供 ArrayAccess,但也提供一个 get() 方法来访问数据。强烈建议使用 get() 方法而不是数组访问,因为 get 方法知道字段映射。

$identity->get('email');
$identity->get('username');

可以通过 IDE 元文件(例如通过 IdeHelper)对 get() 方法进行类型提示。

如果需要,可以使用属性访问,但

$identity->email;
$identity->username;

默认身份对象类可以配置为映射字段。如果身份的标识符不是传统的 id 字段,或者您想将其他字段映射到更通用和常见的名称,这非常有用。

$identity = new Identity($data, [
    'fieldMap' => [
        'id' => 'uid',
        'username' => 'first_name'
    ]
]);

创建您自己的身份对象

默认情况下,身份验证插件会将返回的用户数据包装在 IdentityDecorator 中,该装饰器代理方法和属性访问。如果您想创建自己的身份对象,您的对象必须实现 IdentityInterface

在您的用户类上实现 IdentityInterface

如果您想继续使用此插件的现有用户类,则可以实现 Authentication\IdentityInterface

namespace App\Model\Entity;

use Authentication\IdentityInterface;
use Cake\ORM\Entity;

class User extends Entity implements IdentityInterface
{
    /**
     * Authentication\IdentityInterface method
     */
    public function getIdentifier()
    {
        return $this->id;
    }

    /**
     * Authentication\IdentityInterface method
     */
    public function getOriginalData()
    {
        return $this;
    }

    // Other methods
}

使用自定义身份装饰器

如果您的标识符无法对其生成的物体进行修改以实现 IdentityInterface,则可以实现一个自定义装饰器,该装饰器实现所需的接口。

// You can use a callable...
$identityResolver = function ($data) {
    return new MyCustomIdentity($data);
};

//...or a class name to set the identity wrapper.
$identityResolver = MyCustomIdentity::class;

// Then pass it to the service configuration
$service = new AuthenticationService([
    'identityClass' => $identityResolver,
    'identifiers' => [
        'Authentication.Password'
    ],
    'authenticators' => [
        'Authentication.Form'
    ]
]);