4

我使用cookie中间件1.0没有ASP.NET身份 - 在这篇文章中描述: https://docs.asp.net/en/latest/security/authentication/cookie.html替换值1.0

当用户以一定的变化他/她的个人资料,我需要更改cookie中的一些值。在这样的情况下,这篇文章告诉我

调用context.ReplacePrincipal()和context.ShouldRenew标志 设置为true

究竟是如何做呢?我认为这篇文章是指HttpContext。在HttpContext下看不到ReplacePrincipal()方法。

我很感谢这个帮助。谢谢。

+0

从文章中,'context'看起来像是一个CookieValid atePrincipalContext'。 – DavidG

+0

如何访问CookieValidatePrincipalContext的方法?我一直在做这方面的研究,因为你给了我答案,但我一直无法弄清楚如何使用它。谢谢。 – Sam

+0

https://docs.asp.net/projects/api/en/latest/autoapi/Microsoft/AspNet/Authentication/Cookies/CookieValidatePrincipalContext/ – DavidG

回答

4

在文章中,他们引用了代表中的CookieValidatePrincipalContext代表CookieAuthenticationEvents选项。

你必须连线它在app.UseCookieAuthentication功能startup.cs像这样:

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

而且UpdateValidator功能将类似于:

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; 
    } 
} 

有一个在SecurityStampValidator类一个很好的例子你可以在github上找到:https://github.com/aspnet/Identity/blob/dev/src/Identity/SecurityStampValidator.cs