Agent suggestions
Public previewDescription
Summary
Cookie authentication should not automatically renew a ticket unless principal validation completes with an accepted principal. Make pending renewal state consistent with the final validation outcome—both when validation rejects the principal and when validation throws—while preserving the existing isolation of request-local principal changes from persisted authentication state.
What is wrong
- The desired invariant is that a ticket cannot participate in automatic renewal for a request unless
Events.ValidatePrincipalcompletes normally with a non-nullcontext.Principal. CookieAuthenticationHandlerschedules sliding-expiration renewal (CheckForRefreshAsync) before runningEvents.ValidatePrincipal(context)and maintains pending renewal state (_shouldRefresh,_refreshTicket,_refreshIssuedUtc,_refreshExpiresUtc) separately from the principal-validation outcome.CookieValidatePrincipalContext.RejectPrincipal()changes the request's principal, but it does not communicate cancellation to the handler's pending renewal state, and the handler's rejection branch returnsAuthenticateResults.NoPrincipalwithout cancelling that state.- Similarly, if
Events.ValidatePrincipal(context)throws an exception before completing (for example, during a transient store failure inSecurityStampValidator.ValidateAsyncbeforeRejectPrincipal()andSignOutAsync()are reached), execution unwinds out ofHandleAuthenticateAsyncwith_shouldRefreshstill set and_signOutCalledstillfalse. When exception-handling middleware (such asUseExceptionHandler) catches the exception and writes an error response,FinishResponseAsyncstill runs on response start. FinishResponseAsyncchecks only_shouldRefresh,_signInCalled, and_signOutCalled, without checking whether principal validation succeeded. As a result, response finalization can emit a renewed cookie with updatedIssuedUtcandExpiresUtctimestamps (and renew aSessionStoreentry) even though validation rejected the principal or faulted before completing.
Why it matters (defense in depth)
- Ticket persistence should agree with the validation decision. Authentication state that was rejected or whose validation failed with an unhandled exception should not receive an automatic lifetime extension, a fresh
IssuedUtctimestamp, or a corresponding session-store renewal. - Advancing
IssuedUtcwhen validation throws is particularly undesirable for interval-based validators such asSecurityStampValidator, which compareIssuedUtcagainstValidationIntervalto determine whether subsequent requests must re-verify the principal against the store. - Make successful validation completion a prerequisite for automatic renewal, without removing the separate responsibility of sign-out to delete the browser cookie and remove a stored session.
- The existing Identity security-stamp validator and the documented cookie-validation example reject and sign out on normal validation failure. Preserve that behavior rather than introducing implicit sign-out into
RejectPrincipal()or exception paths.
Affected code
Source references below are pinned to main at 851622243f8aad5d72636142ec2414be966c2449.
- src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs:119-151: pending renewal state and the principal/property snapshot.
- src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs:203-227: pre-validation refresh check,
Events.ValidatePrincipal(context), and the rejected-principal return. - src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs:240-285: response finalization, cookie renewal, and optional session-store renewal.
- src/Security/Authentication/Cookies/src/CookieValidatePrincipalContext.cs:42-46: principal rejection contract.
- src/Identity/Core/src/SecurityStampValidator.cs:136-170:
IssuedUtc-basedValidationIntervalcheck and store verification beforeRejectPrincipal()andSignOutAsync(). - src/Security/Authentication/test/CookieTests.cs:732-758: existing rejection/sign-out coverage, which disables sliding expiration.
- src/Security/Authentication/test/CookieTests.cs:1256-1300: successful renewal coverage protecting principal-transformation isolation.
The same relevant validation and finalization structure is present in the current release/8.0 and release/10.0 handler sources. Backport suitability requires a separate servicing and compatibility decision; no runtime validation was performed on those branches.
Recommended fix
Cancel pending automatic renewal in HandleAuthenticateAsync whenever Events.ValidatePrincipal(context) does not complete with a non-null context.Principal—both when validation leaves context.Principal null (before returning AuthenticateResults.NoPrincipal) and when Events.ValidatePrincipal(context) throws an exception that unwinds HandleAuthenticateAsync. Clear _shouldRefresh and discard _refreshTicket, _refreshIssuedUtc, and _refreshExpiresUtc as a coherent state reset (for example, via a helper invoked in both the context.Principal == null branch and a catch block / exception filter around await Events.ValidatePrincipal(context) before rethrowing). Keep the pre-validation snapshot and the successful-validation path unchanged. Do not add implicit cookie deletion or session-store removal: those remain responsibilities of explicit sign-out.
Alternatives considered:
- Moving snapshot creation after validation would risk persisting request-local principal changes and would conflict with the established transformation-isolation behavior.
- Cancelling pending renewal only inside the
if (context.Principal == null)branch without handling exceptions thrown fromEvents.ValidatePrincipal(context)would still allowFinishResponseAsyncto renew the ticket when exception-handling middleware writes an error response. - Adding an authentication-success gate only in response finalization would leave rejected renewal state live longer and require additional lifecycle bookkeeping. Prefer cancelling the state at the validation boundary (or combining cancellation with a finalization guard).
- Making
RejectPrincipal()sign out would change its request-principal contract and introduce unrelated cookie-deletion and session-store side effects.
No new public or protected signatures, ticket serialization changes, data-protection purpose changes, or stored-session schema changes are proposed. Existing cookies and stored tickets should remain readable without migration. The intentional observable change is suppression of automatic renewal when validation rejects or throws; document and assess that behavior through the normal compatibility process. Preserve successful sliding renewal, explicit successful renewal with a replacement principal, sign-in, and sign-out behavior.
Acceptance criteria
- Rejected principal validation remains a failed authentication result and cancels any pending automatic ticket renewal.
- An exception thrown by
Events.ValidatePrincipalcancels any pending automatic ticket renewal before propagating, so error responses (for example, when handled byUseExceptionHandler) do not emit a renewed cookie or advanceIssuedUtc/ExpiresUtc. - Response finalization emits no renewal cookie and performs no session-store
RenewAsyncoperation when validation rejects the principal or throws. Explicit sign-out may still emit its deletion cookie and remove the stored session. - Add hosted regression coverage in
CookieTeststhat exercises the actual cookie handler, normal renewal eligibility, principal validation, and response finalization. Cover both cookie-only and session-store configurations, and observe authentication and persistence outcomes. - Cover both rejection (
RejectPrincipal()with and without explicit sign-out) andEvents.ValidatePrincipalthrowing an exception when an error response is written, and verify behavior remains correct when no renewal is pending. - Existing successful sliding renewal, explicit successful renewal with a replacement principal, principal-transformation isolation, and sign-in/sign-out coverage remain green.
- Verify the new regression cases fail for the expected persistence outcome before the fix and pass with it; inspect every parameterized case individually.
- Document the intentional behavioral compatibility change and any servicing decision. Confirm that existing ticket formats remain unchanged and no public/protected signature change is introduced.
Investigation evidence is source, history, documentation, and existing-test inspection only. No runtime reproduction or tests were executed for this report. This issue intentionally excludes reproduction code, request sequences, payloads, and exploitation details.
Activity
github-actions commentedon Oct 7, 2026
Triage Summary
Area:
area-auth(CookieAuthenticationHandler/CookieValidatePrincipalContextinsrc/Security/Authentication/Cookies)Type:
Task(bounded hardening of pending-renewal state; the issue states authentication already fails for the rejected principal)Potential Duplicates
Notes
AllowRefreshis false), with open PR Respect AllowRefresh in SecurityStampValidator cookie renewal #65803. It concernsAllowRefreshinSecurityStampValidator, not cancelling renewal afterRejectPrincipal().rokonec commentedon Nov 5, 2026
@GrantTotinov I have just today updated this issue and find out there is already PR for it. Can you please address changed description. In particular section
GrantTotinov commentedon Nov 5, 2026
@rokonec Sure, boss. I will do it tonight.
GrantTotinov commentedon Nov 7, 2026
@rokonec Updated #70028 to cover the exception path as well.