替换Cookie ASP.NET Core 1.0中的值 [英] Replace value in cookie ASP.NET Core 1.0

查看:161
本文介绍了替换Cookie ASP.NET Core 1.0中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

我该怎么做?我认为本文指的是HttpContext.我在HttpContext下看不到ReplacePrincipal()方法.

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.

推荐答案

在本文中,他们从CookieAuthenticationEvents选项中的OnValidatePrincipal委托引用了CookieValidatePrincipalContext.

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

您必须像这样在startup.cs中的app.UseCookieAuthentication功能中将其连接起来:

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

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

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

这篇关于替换Cookie ASP.NET Core 1.0中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆