I'm using the ASP.NET framework CookieAuthenticationProvider to generate an identity with AspNet.Identity.Core version 2.2.2.
The cookie seems to be correctly generated when I look at it from the front end (the CookieName, CookieDomain are all like expected).
However, I want the cookie to be refreshed after every X seconds. On the Microsoft docs its stated that I can use the OnValidateIdentity property on the CookieAuthenticationProvider object for this, however the regenerationIdentityCallback does not seem to get triggered ever.
One important thing to mention is that we use an int variable as TKey in the UserManager<TUser, TKey> instead of a GUID (which is the standard as far as I'm aware)
The current code looks like this:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Identity.Application",
CookieName = $".AspNet.SharedCookie-{environment}",
CookieDomain = ".example.com",
LoginPath = new PathString("/"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity =
SecurityStampValidator
.OnValidateIdentity<UserManager<User, int>, User, int>(
validateInterval: TimeSpan.FromSeconds(30),
regenerateIdentityCallback: async (manager, user) =>
{
var identity = await manager.CreateIdentityAsync(user, "Identity.Application");
return identity;
},
getUserIdCallback: (user) => Int32.Parse(user.GetUserId()))
},
TicketDataFormat = new AspNetTicketDataFormat(
new DataProtectorShim(
DataProtectionProvider.Create(keyRingFolderInfo, (builder) => { builder.SetApplicationName($"{environment}-{applicationName}"); })
.CreateProtector(
"Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware",
"Identity.Application",
"v2"))),
CookieManager = new ChunkingCookieManager()
});
Why does the ValidateInterval not regenerate the identity every 30 seconds? And how else should I get this to work how I want it to?
Since you have a int key, you have implemented a custom UserManager, UserStore, (...)
When you implement your own logic you also have to implement this interface:
[IUserSecurityStampStore<TUser, in TKey>]
in your custom UseStore class (more infos about this interface).
Here you can see the default Implementation of SecurityStampValidator.
// Only validate if enough time has elapsed
var validate = (issuedUtc == null);
if (issuedUtc != null)
{
var timeElapsed = currentUtc.Subtract(issuedUtc.Value);
validate = timeElapsed > validateInterval;
}
if (validate)
{ ..... await regenerateIdentityCallback.Invoke(manager, user).WithCurrentCulture()
As you can see, this class makes the decision to call the regenerateIdentityCallback Method. Debug this method and you will see why regenerateIdentityCallback is called or not.