Replace cookie value in ASP.NET Core 1.0

I use cookie middleware in ASP.NET Core 1.0 without an ASP.NET identifier - as described in this article: https://docs.asp.net/en/latest/security/authentication/cookie.html

When a user makes certain changes to their profile, I need to change some values ​​in the cookie. In such scenarios, this article tells me

call the context .ReplacePrincipal () and set the context.ShouldRenew flag to true

How exactly am I doing this? I think the article refers to the HttpContext. I do not see the ReplacePrincipal () method in the HttpContext.

I would be grateful for your help in this. Thank.

+4
source share
1 answer

In the article, they refer to CookieValidatePrincipalContextfrom the delegate OnValidatePrincipalin the options CookieAuthenticationEvents.

You need to connect it to functions app.UseCookieAuthenticationin startup.csthis way:

app.UseCookieAuthentication(options =>
{
     //other options here
     options.Events = new CookieAuthenticationEvents
     {
          OnValidatePrincipal = UpdateValidator.ValidateAsync
     };     
 });

And the function UpdateValidatorwill look like this:

public static class UpdateValidator
{
    public static async Task ValidateAsync(CookieValidatePrincipalContext context)
    {
        //check for changes to profile here

        //build new claims pricipal.
        var newprincipal = new System.Security.Claims.ClaimsPrincipal();

        // set and renew
        context.ReplacePrincipal(newprincipal);
        context.ShouldRenew = true;
    }
}

There SecurityStampValidatoris a good example in the class that you can find on github: https://github.com/aspnet/Identity/blob/dev/src/Identity/SecurityStampValidator.cs

+4
source

All Articles