I'm just getting started with OWIN and ASP.net Identity. This is how I am signing in my users:
ClaimsIdentity identity = new ClaimsIdentity(
new Claim[] {
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Email, user.Email),
new Claim(ClaimTypes.GivenName, user.FirstName),
new Claim(ClaimTypes.Surname, user.LastName),
}, "ApplicationCookie");
foreach(Role role in user.Roles)
{
identity.AddClaim(new Claim(ClaimTypes.Role, role.Name));
}
var owinContext = Request.GetOwinContext();
var authManager = owinContext.Authentication;
authManager.SignIn(new AuthenticationProperties() { IsPersistent = model.RememberMe }, identity);
This works and the roles are all wired up correctly. My question is: If the user logs in and has one set of roles, then their roles are updated in the system (perhaps by a system admin), how do you invalidate and re-populate the user's auth cookie?
In your Startup.cs
file you can register a CookieAuthenticationProvider
that will invalidate and regenerate a new cookie for the user after a certain time period
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator
.OnValidateIdentity<UserManager, ApplicationUser, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager)
}
});