Skip to content

Keep Router::getRequest() in sync with the authenticated request - #826

Merged
markstory merged 1 commit into
cakephp:4.xfrom
bancer:4.x-update-global-request
Nov 19, 2026
Merged

markstory merged 1 commit into
cakephp:4.xfrom
bancer:4.x-update-global-request

Conversation

@bancer

@bancer bancer commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

Problem

AuthenticationMiddleware adds the identity, authentication and authenticationResult attributes to the request, but does not store the new request in Router. Until BaseApplication::handle() calls Router::setRequest(), Router::getRequest() returns the request stored by RoutingMiddleware, which has no identity.

ErrorHandlerMiddleware renders exceptions for Router::getRequest() ?? $request. So when a middleware placed after AuthenticationMiddleware throws, the error page is rendered without the identity: ErrorController has no authentication attribute, IdentityHelper reports a guest, and error trackers get no user. Session users can be recovered by reading the session again. Users of stateless authenticators (token, HTTP Basic, environment) cannot.

AuthenticationComponent has the same gap. Methods that replace the controller's request don't update Router. If an action throws after setIdentity() or logout(), the error page shows the identity from before the change.

Changes

  • AuthenticationMiddleware::process() calls Router::setRequest() after setting the attributes. As in AuthenticationService, it does this only for a ServerRequest and only when Router exists, so the middleware still works outside the CakePHP framework.
  • AuthenticationComponent gets a protected updateRequest() helper that sets the request on the controller and on Router. It is used by setIdentity(), replaceIdentity(), logout(), impersonate() and stopImpersonating().

Tests

  • New AuthenticationMiddlewareTest::testRouterRequestIsUpdated checks that Router::getRequest() has the authenticated identity, the service and the result after the middleware runs.
  • testSetIdentity, testReplaceIdentity and testLogout in AuthenticationComponentTest now also check that Router::getRequest() matches the controller's request.

Notes

Overlaps with #802 in setIdentity().

@markstory markstory added this to the 4.x milestone Nov 19, 2026
@markstory
markstory merged commit a6c9ecc into cakephp:4.x Nov 19, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants