Skip to content

Allow rotating the cookie session key on sign-in - #70105

Open
earbona23 wants to merge 4 commits into
dotnet:mainfrom
earbona23:rotate-session-key-on-signin
Open

earbona23 wants to merge 4 commits into
dotnet:mainfrom
earbona23:rotate-session-key-on-signin

Conversation

@earbona23

@earbona23 earbona23 commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Allow rotating the cookie session key on sign-in

Addresses #47503. API proposal: #70373.

Problem

When CookieAuthenticationOptions.SessionStore is configured, ReadCookieTicket caches the
session key that arrived on the request:

https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authentication/Cookies/src/CookieAuthenticationHandler.cs#L178

HandleSignInAsync then renews the ticket under that same key rather than minting a new one,
which is the behavior #22732 introduced for #22135:

if (_sessionKey != null)
{
    // Renew the ticket in cases of multiple requests see: https://github.com/dotnet/aspnetcore/issues/22135
    await Options.SessionStore.RenewAsync(_sessionKey, ticket, Context, Context.RequestAborted);
}

So a sign-in that changes who the principal is stores the new ticket under a key that an
earlier cookie already holds, and that earlier cookie keeps resolving to the new ticket. That is
the session fixation concern in #47503, and OWASP's session management guidance asks for the
session id to be renewed on any privilege level change.

#67049 fixed the sign-out leg by clearing _sessionKey, which covers SignOutAsync followed by
SignInAsync in one request. It does not cover a bare SignInAsync — which is what ASP.NET Core
Identity does on password sign-in, since SignInManager.SignInWithClaimsAsync calls
Context.SignInAsync without signing the application scheme out first.

Change

Adds an opt-in AuthenticationProperties.RotateSessionKey. When set, the handler removes the
incoming key from the store before storing the new ticket, so the previous key stops resolving:

if (_sessionKey != null && signInContext.Properties.RotateSessionKey == true)
{
    await Options.SessionStore.RemoveAsync(_sessionKey, Context, Context.RequestAborted);
    _sessionKey = null;
}

The default is unchanged. Without the flag the key is still renewed in place, so concurrent
requests holding the same cookie keep working and #22135 stays fixed.

Why opt-in rather than automatic

The privilege-rotation case in #47503 signs in the same subject with different claims. That is
indistinguishable from the refresh case in #22135, which also signs in the same subject. Any
automatic rule based on comparing the incoming and outgoing principal would either miss the
privilege change or break the refresh, so the caller has to say which one it means. This matches
what was suggested in #67049:

The larger question — whether SignInAsync should always rotate the session key (and how to
preserve the refresh case from #22135) — is left for that issue, where it needs its own design
discussion (likely an opt-in AuthenticationProperties flag).

I am happy to move the flag out of Microsoft.AspNetCore.Authentication.Abstractions and into the
cookie package (for example as extension methods over AuthenticationProperties.Items) if adding
to the shared type is not wanted. This adds public API, so it needs API review.

Tests

SignInRotatesSessionKeyOnlyWhenRequested is a [Theory] over both values of the flag. It
establishes a session as Alice, then signs in as Bob while Alice's cookie is attached to the
request — no sign-out — and asserts:

  • with the flag: the store key changes, and Alice's original cookie no longer authenticates;
  • without the flag: the store key is unchanged and the original cookie still authenticates,
    i.e. current behavior;
  • in both cases, the cookie returned by the sign-in response authenticates as Bob.

When CookieAuthenticationOptions.SessionStore is configured, the handler caches
the session key from the incoming cookie in _sessionKey and a subsequent
SignInAsync renews the ticket under that same key (dotnet#22135). A sign-in that
changes who the principal is therefore stores the new ticket under a key an
earlier cookie already holds, so that cookie keeps resolving to the new ticket.

dotnet#67049 fixed the sign-out leg of this by clearing _sessionKey, which covers
SignOutAsync followed by SignInAsync in one request. It does not cover a bare
SignInAsync, which is what ASP.NET Core Identity does on password sign-in.

Add an opt-in AuthenticationProperties.RotateSessionKey so a caller can ask for
a fresh session key. When set, the handler removes the incoming key from the
store before storing the new ticket, so the previous key no longer resolves.
The default is unchanged: without the flag the key is still renewed in place and
concurrent requests holding the same cookie keep working.

The flag is opt-in rather than automatic because the privilege-rotation case in
dotnet#47503 signs in the same subject with different claims, which is
indistinguishable from the refresh case in dotnet#22135.

Addresses dotnet#47503.
@github-actions github-actions Bot added the area-auth Includes: authentication, authorization, OAuth, OIDC, and access token validation label Oct 29, 2026
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Oct 29, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Thanks for your PR, @earbona23. Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@earbona23

Copy link
Copy Markdown
Contributor Author

Status check from my side, in case this is waiting on something I can do.

The branch is mergeable and the checks are settled: 28 of the 30 are green and the other two are neutral. The state is blocked, which I read as waiting on review rather than on the build.

Since the change adds a public member, AuthenticationProperties.RotateSessionKey, and touches PublicAPI.Unshipped.txt, I assume it needs to go through API review before it can be looked at as code. If that is the case I am glad to open an API proposal issue with the shape and the rationale, so this PR is only the implementation.

I am also happy to change the shape if the team prefers something else. Two alternatives I considered and did not pick:

  • doing the rotation unconditionally on SignInAsync when a SessionStore is configured, which is the behaviour OWASP asks for but would be a breaking change for anyone relying on the current renew semantics from Cookie authentication handler overwrites session key when signing in #22135
  • putting the switch on CookieAuthenticationOptions rather than on AuthenticationProperties, which is simpler but cannot be scoped to the sign-in that changes the principal

The opt-in property was the least disruptive of the three. I will follow whichever the team prefers.

@PureWeen

PureWeen commented Nov 2, 2026

Copy link
Copy Markdown
Member

/review

Brings the branch up to date with main. No conflicts: none of the four files
this branch changes were touched upstream since the fork point.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed frozen head 570ba24245f66801cf08156ecaa8bb8f0ae40529 using the immutable bundle guidance at 480401c0a53ddd2e52d2ad34aaef4424edfead21.

One validated P2 finding is attached: remove-before-store does not guarantee rotation for an ITicketStore that reuses a released identifier. Frozen feedback contained no equivalent report. API-review approval for the new public member remains human-owned and unresolved; this is not a code finding.

The cross-cutting guide completed with gpt-5.6-sol (runtime effort telemetry unavailable). Cookie-auth-specific specialist coverage was not routed. Worker execution and security assessment were excluded by the trusted guidance.

Coordinator validation used the exact frozen-head worktree and a temporary CookieTests.cs repro with a key-reusing store. The final targeted test ran 1 case and failed at the observable cookie boundary: replaying Alice's original cookie returned Bob. Repository-pinned SDK setup and generated-file setup were required before the test could run. No repository-wide suite was run. Source limitations remain tracked Git bytes only; symlink, submodule, and LFS targets were not evaluated.

Generated by ASP.NET Core Pull Request Review for #70105 · copilot · gpt56 · 162 AIC · ⌖ 12.2 AIC · ⊞ 20K
Comment /review to run again

// See https://github.com/dotnet/aspnetcore/issues/47503.
if (_sessionKey != null && signInContext.Properties.RotateSessionKey == true)
{
await Options.SessionStore.RemoveAsync(_sessionKey, Context, Context.RequestAborted);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 — Require a distinct key before deleting the old session

ITicketStore.StoreAsync only promises to return the associated key; it does not promise a fresh one. Because this removes the old key before calling StoreAsync, a conforming store that recycles released identifiers can immediately return _sessionKey again. The old cookie then resolves to the newly stored ticket even though RotateSessionKey was requested. A targeted repro using a store that reuses its last removed key failed with the replayed Alice cookie authenticating as Bob. Please allocate/store while the old key is still reserved and enforce a distinct result before removing it, or add an atomic/fresh-key store contract, and cover the key-reuse case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 0617d43. Rotation now keeps the incoming session key reserved, stores the new ticket, and removes the old key only once StoreAsync has returned a different one, so a store that recycles released keys cannot hand the incoming key straight back. Added SignInRotatesSessionKeyWhenStoreRecyclesReleasedKeys, which uses a key-recycling store and fails on the previous commit, and merged the branch up to main.

ITicketStore.StoreAsync only promises to return the key the ticket was stored
under, not a key that has never been used before. Removing the incoming key
before calling StoreAsync therefore let a store that recycles released keys
hand the incoming key straight back, so the cookie that came in on the request
still resolved to the newly stored ticket and nothing was rotated.

Keep the incoming key reserved, store the new ticket, and release the old key
only once the new one differs from it. Add a regression test with a store that
recycles the keys it releases.
@earbona23

Copy link
Copy Markdown
Contributor Author

Correction to my status comment above: the "28 of the 30 are green" line described 570ba242, which
was the head when I wrote it. I pushed two commits after that, so the number no longer describes this
PR. Current state on b9b9b00: 23 success, 5 failure, 2 neutral.

The five red checks are two distinct failing jobs plus three roll-ups of those two:

check what it actually is
aspnetcore-components-e2e (Test: Blazor E2E tests on Linux (Mono server)) a failing job
aspnetcore-components-e2e (Test: Blazor E2E tests on Linux (Mono client and WebAssembly)) a failing job
aspnetcore-components-e2e the parent of those two
Build Analysis, Build Insights report the two above

I do not think either job is failing because of this change. The evidence rather than the assertion:

The Mono client and WebAssembly leg is red far less often — I saw it on #70311, #70290 and #70261 —
and I could not read the failing test names from the build logs, so I am not claiming it is the same
flake with the same confidence. I can only say the diff has no path into Blazor.

I cannot trigger a re-run myself. Happy for one to be kicked, or to rebase onto current main if a
fresh run is preferred.

Separately, and not about CI: the automated review flagged that removing the incoming key before
StoreAsync does not guarantee rotation for an ITicketStore that recycles released keys. That was
a real hole. 0617d43 stores the new ticket first and releases the old key only once it differs,
with a regression test that uses a key-recycling store.

The offer in my earlier comment still stands: AuthenticationProperties.RotateSessionKey is a new
public member, so if this should go through API review I will open the proposal issue with the shape
and the rationale and leave this PR as the implementation only.

@earbona23

Copy link
Copy Markdown
Contributor Author

Following up on my own offer above rather than leaving it as a question: the API proposal is filed as #70373, and this PR's description now links it.

I went ahead because docs/APIReviewProcess.md puts that step on the author, not on the reviewer:

When opening an implementation pull request that adds or changes public API, use the api-review skill to file a separate API proposal issue.

So the gap was mine. #70373 follows the api-review skill's template: background, the ref-assembly diff for AuthenticationProperties.RotateSessionKey, usage examples, the two alternative designs I considered and why I did not take them, the risks, and per-claim source quotes.

Two things there that need someone with write access:

  • The issue carries no labels. gh dropped api-suggestion and api-proposal silently because I cannot label in this repo, and the Feature issue type is not set either. Whoever triages it, please add them.
  • api-ready-for-review and notifying @dotnet/aspnet-api-review are an area-auth owner's call, not mine. I can attend the review meeting to represent the proposal if that helps, but I cannot be the champion.

Nothing else is outstanding on the code. The P2 from the automated review is fixed in 0617d43 with a key-recycling-store test, and the two red aspnetcore-components-e2e legs are red on main as well, with the evidence in my comment above. This PR touches no file under src/Components.

Happy to change the API shape to whatever the review prefers, including moving the flag off AuthenticationProperties onto something cookie-specific, which is the one point in #70373 I flagged for the reviewers' attention myself.

@earbona23

Copy link
Copy Markdown
Contributor Author

Correcting my own comment above, because it is already out of date: I wrote that #70373 carries no labels and no issue type. That was true when I posted it and stopped being true four minutes later — the triage bot applied api-proposal and area-auth, and set the Feature issue type.

So the only one still missing is api-suggestion, which docs/APIReviewProcess.md asks for alongside api-proposal. Smaller ask than the one I just made.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Looks like this PR hasn't been active for some time and the codebase could have been changed in the meantime.
To make sure no conflicting changes have occurred, please rerun validation before merging. You can do this by leaving an /azp run comment here (requires commit rights), or by simply closing and reopening.

@dotnet-policy-service dotnet-policy-service Bot added the pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun label Nov 14, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-auth Includes: authentication, authorization, OAuth, OIDC, and access token validation community-contribution Indicates that the PR has been added by a community member pending-ci-rerun When assigned to a PR indicates that the CI checks should be rerun

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants