I am having trouble getting ASP Identity to refresh its Identity stored in a cookie on demand.
In the Startup.Auth.cs
file the cookie is set to regenerate as follows:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<QuizSparkUserManager, QuizSparkUser, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: ((manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)),
getUserIdCallback: ((claimsIdentity) => int.Parse(claimsIdentity.GetUserId())))
}
});
However I cannot work out how to refresh the contents on User.Identity
in code, i.e. force a refresh of the identity cookie when I need it to refresh.
I want to be able to use the regenerate identity callback programmatically, is this possible?
My problem is similar to this one : How to invalidate .AspNet.ApplicationCookie after Adding user to Role using Asp.Net Identity 2?
However I want to refresh rather than invalidate the cookie.
Edit
After looking at the linked question I attempted the following (without full error handling):
IOwinContext context = Request.GetOwinContext();
QuizSparkSignInManager manager = context.Get<QuizSparkSignInManager>();
ClaimsIdentity newIdentity = manager.CreateUserIdentity(manager.UserManager.FindById(User.Identity.GetUserId<int>()));
AuthenticateResult authenticationContext =
await context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie);
if (authenticationContext != null)
{
context.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant(
newIdentity, authenticationContext.Properties);
}
bool first2 = User.IsInRole("Turtle");
Edit2: However the User still does not appear to refresh. On page reload they do seem to refresh, am I right in thinking this is because User.Identity cookie is part of the request and cannot be changed in code?