【问题标题】:Replace value in cookie ASP.NET Core 1.0替换 cookie ASP.NET Core 1.0 中的值
【发布时间】:2016-07-04 13:22:34
【问题描述】:

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

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

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

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

我很感激这方面的帮助。谢谢。

【问题讨论】:

标签: asp.net-mvc cookies asp.net-core-mvc asp.net-authentication asp.net-core-1.0


【解决方案1】:

在文章中,他们在 CookieAuthenticationEvents 选项中引用了来自 OnValidatePrincipal 委托的 CookieValidatePrincipalContext

您必须像这样在startup.csapp.UseCookieAuthentication 函数中连接它:

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

【讨论】:

    猜你喜欢
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多