替换 cookie 中的值 ASP.NET Core 1.0

Sam*_*Sam 4 cookies asp.net-mvc asp.net-authentication asp.net-core-mvc asp.net-core-1.0

我在没有 ASP.NET Identity 的 ASP.NET Core 1.0 中使用 cookie 中间件 - 如本文所述: https ://docs.asp.net/en/latest/security/authentication/cookie.html

当用户对其个人资料进行某些更改时,我需要更改 cookie 中的某些值。在这种情况下,这篇文章告诉我

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

我到底该怎么做?我认为这篇文章指的是HttpContext。我在 HttpContext 下没有看到 ReplacePrincipal() 方法。

我希望得到一些帮助。谢谢。

jst*_*ant 5

在文章中,他们在选项中引用了CookieValidatePrincipalContext委托。OnValidatePrincipalCookieAuthenticationEvents

您必须将其连接到app.UseCookieAuthentication函数中startup.cs,如下所示:

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

该类中有一个很好的示例SecurityStampValidator ,您可以在 github 上找到: https: //github.com/aspnet/Identity/blob/dev/src/Identity/SecurityStampValidator.cs