diff --git a/docs/en/authentication-component.md b/docs/en/authentication-component.md index 909026ab..2f8142dd 100644 --- a/docs/en/authentication-component.md +++ b/docs/en/authentication-component.md @@ -102,6 +102,24 @@ The result returned will contain an array like this: > context you're working in you'll have to use these instances from now on if you > want to continue to work with the modified response and request objects. +## Replacing the current identity + +Use `setIdentity()` to change which user is logged in (e.g. after registration +or social-login first-touch). It clears all persisted identity data and writes +the new identity through every persisting authenticator: + +```php +$this->Authentication->setIdentity($user); +``` + +> [!WARNING] +> `setIdentity()` ends an active impersonation session because it goes through +> `clearIdentity()` first, which calls `stopImpersonating()` on +> impersonation-aware authenticators. If you only need to refresh the active +> identity object on the current request (for example, to eager-load +> associations), set the `identity` request attribute directly instead - see +> [User Impersonation](impersonation.md) for an example. + ## Configure Automatic Identity Checks By default `AuthenticationComponent` will automatically enforce an identity to diff --git a/docs/en/impersonation.md b/docs/en/impersonation.md index 2ed83075..f0389e8f 100644 --- a/docs/en/impersonation.md +++ b/docs/en/impersonation.md @@ -67,3 +67,25 @@ There are a few limitations to impersonation. 1. Your application must be using the `Session` authenticator. 2. You cannot impersonate another user while impersonation is active. Instead you must `stopImpersonating()` and then start it again. +3. Calling `setIdentity()` or `clearIdentity()` (and therefore `logout()`) + ends impersonation. The service's `clearIdentity()` actively calls + `stopImpersonating()` on impersonation-aware authenticators, so any code + path that swaps the persisted identity will revert you to the original + user. To refresh the in-request identity object without disturbing + impersonation - for example, to eager-load associations on the active + user in `beforeFilter()` - write to the request attribute directly: + + ```php + use Authentication\Identity; + + $identity = $this->Authentication->getIdentity(); + $reloaded = $this->fetchTable('Users') + ->get($identity->getIdentifier(), finder: 'fullProfile'); + + $this->setRequest( + $this->getRequest()->withAttribute('identity', new Identity($reloaded)) + ); + ``` + + This updates the identity for the remainder of the current request only + and leaves the session - and any active impersonation - untouched.