setIdentity() 后为何报 No AuthenticationProvider present?
使用内置 Session authenticator 时,可以在调用 setIdentity() 后,通过 AuthenticationService::authenticate() 重新认证并记录成功的 provider,再恢复原有的 impersonation。如果只连续调用 setIdentity() 和 impersonate(),就会缺少 impersonate() 所需的 provider。
为什么会出现这个错误?
AuthenticationComponent::setIdentity() 会先调用 clearIdentity(),再调用 persistIdentity(),以清除并替换身份。清除身份时,已有的 impersonation 也会结束。AuthenticationComponent 3.x 源码
clearIdentity() 还会将记录成功认证器的 _successfulAuthenticator 设为 null。之后,persistIdentity() 会保存身份,但不会重新设置这个成员。此时调用 impersonate(),其内部获取 provider 时就会抛出 No AuthenticationProvider present.。AuthenticationService 3.x 源码
在这个调用顺序下,错误表示当前请求没有记录成功认证的 provider。不能单凭这条错误判断应用没有加载 authenticator。
如何更新资料后恢复 impersonation?
下面的示例对两个变量作了以下假设:
$user是发起 impersonation 的真实用户,包含已成功保存的最新个人资料。$user2是原先被 impersonate 的目标用户,从服务端可信数据中取得,并实现ArrayAccess,例如 CakePHP ORM entity。
原问题没有完全说明变量的身份关系。如果实际修改的是目标用户的资料,需要调整流程,避免把目标用户误设为发起者。
更新身份前,先记录当前是否正在 impersonating。然后更新真实用户的身份,重新认证,再恢复原目标用户。以下代码在资料保存成功后执行,前提是当前请求已经通过 Session authenticator 成功认证:
// Record the state before setIdentity() clears it.
$wasImpersonating = $this->Authentication->isImpersonating();
// $user is the real user with successfully saved profile data.
$this->Authentication->setIdentity($user);
if ($wasImpersonating) {
$service = $this->Authentication->getAuthenticationService();
$result = $service->authenticate($this->getRequest());
if (!$result->isValid()) {
throw new \RuntimeException('Unable to authenticate the updated identity.');
}
$provider = $service->getAuthenticationProvider();
if (!($provider instanceof \Authentication\Authenticator\ImpersonationInterface)) {
throw new \RuntimeException('The authenticator does not support impersonation.');
}
// $user2 is the previously impersonated user.
$this->Authentication->impersonate($user2);
}
authenticate() 会按已配置的 authenticators 重新认证,并记录成功的 provider。请确保 Session 已加载,且优先于其他可能提前认证成功的 authenticators。代码也检查了认证结果和 authenticator 是否支持 impersonation。
这一处理方式依据前述 3.x 源码中的调用关系,具体行为仍需对照项目安装的小版本确认。
使用时需要注意什么?
setIdentity() 不负责将个人资料保存到数据库。应先完成数据库保存,再将可信的最新用户数据传入身份更新流程。
恢复 impersonation 前,仍需确认真实用户有权 impersonate 原目标用户,尤其是在更新个人资料的同时涉及权限变更时。Authentication 的内置 impersonation 要求使用 Session authenticator,也不允许在已有 impersonation 上直接嵌套新的 impersonation。官方 User Impersonation 文档
恢复后建议重定向到业务已有的 GET 页面。内置 SessionAuthenticator::impersonate() 会更新 Session,但其实现返回的是原 request;下一次请求才会重新读取目标用户作为活动身份。因此,不要假定同一请求中的 getIdentity() 已经切换为 $user2。SessionAuthenticator 3.x 源码
备注:内容仅供参考。
