Passing the current ClaimsIdentity to the regenerateIdentity callback

I wanted to persist some extra claims that weren't driven directly from the database. That was all well and good until the user identity was refreshed and the extra claims were lost.

The template code for Startup.cs looks like this:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        // Enables the application to validate the security stamp when the user logs in.
        // This is a security feature which is used when you change a password or add an external login to your account.  
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});      

It turns out that getting the current Identity is really simple by using your own Func<CookieValidateIdentityContext, Task> instead of using the one provided by the SecurityStampValidator class. That looks a bit like this:

OnValidateIdentity = async context =>
    {
        var securityStampOnValidateIdentity =
            SecurityStampValidator
                .OnValidateIdentity<ApplicationUserManager, AspIdentityUser>(
                    validateInterval: TimeSpan.FromMinutes(20),
                    regenerateIdentity: (manager, user) =>
                        {
                            var identity = myContainer
                                    .Get<IIdentityService>()
                                    .RefreshIdentity(user, context.Identity);
                            return Task.FromResult(identity);
                        });
        await securityStampOnValidateIdentity.Invoke(context);
    }

Now my IIdentityService.RefreshIdentity can know about the current ClaimsIdentity simply by using the context.Identity. That means I can add my extra, non database persisted claims, back to the new identity.

Comments

Popular posts from this blog

Trimming strings in action parameters in ASP.Net Web API

Full text search in Entity Framework 6 using command interception

Composing Expressions in C#