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