Repository navigation
Why is cookie expiration tied to Cognito token expiration, and how should longer “Remember me” sessions be implemented? #323
QuestionI’m using I’d like to understand the design behind coupling the application authentication cookie’s expiration to the Cognito token expiration, and the supported approach for longer persistent “Remember me” sessions. Desired behaviorWhen a user selects “Remember me,” we want them to remain signed in for a fixed maximum of 30 days, including after closing the browser and returning several days later. Access and ID tokens would retain their normal, shorter lifetimes. When necessary, the application would use the refresh token to obtain replacements. If refresh is rejected or the application session reaches its 30-day limit, the user would need to sign in again. Current behavior
ExpiresUtc = user.SessionTokens?.ExpirationTime,
IssuedUtc = user.SessionTokens?.IssuedTime
Consequently, configuring a longer cookie My understanding is that if a user returns after the authentication ticket expires, normal cookie authentication rejects the ticket, even though the refresh token stored within it might still be valid. I also noticed that What I’d like to understand
Our current workaroundWe currently override the ticket expiration during cookie signing to preserve a fixed 30-day session boundary. We separately restore the actual token issue and expiration dates from the access token before deciding whether to refresh. Before relying on this approach, I’d like to understand whether it conflicts with assumptions in the library and whether there is an officially supported alternative. Are there particular requirements around revocation, account changes, or principal validation when allowing the application cookie to outlive the Cognito access/ID tokens? I found related discussions in #122 and #221, but I’m still unclear on the rationale for the coupling and the recommended implementation for longer persistent sessions. Thank you for any clarification or examples. |
Replies: 1 comment
|
The coupling is an implementation choice, not a Cognito security requirement. The library uses the auth ticket as its only token store, so the ticket dates double as the token dates. There's no built-in long-session mode, but your workaround is the right direction. Answers in your order: 1. Why the lifetimes are coupledThe library has nowhere else to keep the token timestamps:
So to the library, 2. What "Remember me" means here
3. A 30-day session with short-lived tokensNot built in, but it works with three rules:
4. Extension pointsA sign-in manager subclass to stamp the dates, plus cookie events to refresh. public class LongSessionSignInManager : CognitoSignInManager<CognitoUser>
{
public LongSessionSignInManager(UserManager<CognitoUser> userManager, IHttpContextAccessor contextAccessor,
IUserClaimsPrincipalFactory<CognitoUser> claimsFactory, IOptions<IdentityOptions> optionsAccessor,
ILogger<SignInManager<CognitoUser>> logger, IAuthenticationSchemeProvider schemes,
IUserConfirmation<CognitoUser> confirmation)
: base(userManager, contextAccessor, claimsFactory, optionsAccessor, logger, schemes, confirmation) { }
// Both SignInAsync and RefreshSignInAsync end up here, with ExpiresUtc = token expiry.
public override Task SignInWithClaimsAsync(CognitoUser user, AuthenticationProperties props, IEnumerable<Claim> claims)
{
if (props?.IsPersistent == true)
{
props.Items["token_expires_utc"] = props.ExpiresUtc?.ToString("o");
props.Items.TryAdd("session_start_utc", DateTimeOffset.UtcNow.ToString("o")); // kept on refresh
props.ExpiresUtc = DateTimeOffset.Parse(props.Items["session_start_utc"]!).AddDays(30);
}
return base.SignInWithClaimsAsync(user, props, claims);
}
}
// after services.AddCognitoIdentity()
services.AddScoped<SignInManager<CognitoUser>, LongSessionSignInManager>();
services.ConfigureApplicationCookie(o =>
{
o.SlidingExpiration = false;
o.Events.OnValidatePrincipal = async ctx =>
{
var items = ctx.Properties.Items;
if (!items.TryGetValue("session_start_utc", out var start)) return; // non-persistent session
if (DateTimeOffset.Parse(start!).AddDays(30) < DateTimeOffset.UtcNow)
{
ctx.RejectPrincipal();
await ctx.HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);
return;
}
var tokenExpires = DateTimeOffset.Parse(items["token_expires_utc"]!);
if (tokenExpires > DateTimeOffset.UtcNow.AddMinutes(5)) return;
try
{
// InitiateAuth with REFRESH_TOKEN_AUTH using ctx.Properties.GetTokenValue("refresh_token"),
// then UpdateTokenValue("access_token" / "id_token") and set items["token_expires_utc"].
ctx.ShouldRenew = true;
}
catch (NotAuthorizedException) // refresh token expired or revoked, user disabled
{
ctx.RejectPrincipal();
await ctx.HttpContext.SignOutAsync(IdentityConstants.ApplicationScheme);
}
};
});Blazor Server caveat: 5. Revocation and account changesOnce the cookie outlives the tokens, the refresh is your only revocation check. A global sign-out or a disabled user makes the refresh fail. If you refresh as soon as the access token expires, you catch it within one token lifetime. So keep access tokens short, and always reject the principal when a refresh fails.
|
The coupling is an implementation choice, not a Cognito security requirement. The library uses the auth ticket as its only token store, so the ticket dates double as the token dates. There's no built-in long-session mode, but your workaround is the right direction. Answers in your order:
1. Why the lifetimes are coupled
The library has nowhere else to keep the token timestamps:
SignInAsyncandRefreshSignInAsyncwrite them into the ticket (CognitoSigninManager.cs#L161-L229).PopulateTokensreads them back to rebuildCognitoUserSessionon everyFindBy*Async(CognitoUserManager.cs#L166).So to the library,
ExpiresUtcis the token expiry, and the cookie handler enforces that same date. One…