4

I'm using the cookie middleware in ASP.NET Core 1.0 without ASP.NET Identity - as described in this article: https://docs.asp.net/en/latest/security/authentication/cookie.html

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

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

How exactly do I do that? I think the article is referring to HttpContext. I don't see a ReplacePrincipal() method under HttpContext.

I'd appreciate some help with this. Thanks.

Sam
  • 26,817
  • 58
  • 206
  • 383
  • From the article, `context` looks like it's a `CookieValidatePrincipalContext`. – DavidG Mar 17 '16 at 23:20
  • How do I access the methods of CookieValidatePrincipalContext? I've been doing some research on this since you gave me the answer but I haven't been able to figure out how to use it. Thanks. – Sam Mar 17 '16 at 23:42
  • https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNet/Authentication/Cookies/CookieValidatePrincipalContext/ – DavidG Mar 18 '16 at 00:13

1 Answers1

5

In the article they are referencing the CookieValidatePrincipalContext from the OnValidatePrincipal delegate in the CookieAuthenticationEvents options.

You have to wire it up in the app.UseCookieAuthentication function in startup.cs like so:

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

And the UpdateValidator function would look like:

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 is a good example in the SecurityStampValidator class which you can find on github: https://github.com/aspnet/Identity/blob/dev/src/Identity/SecurityStampValidator.cs

Community
  • 1
  • 1
jsturtevant
  • 2,560
  • 1
  • 23
  • 23