ASP.netCORE3中如何更新身份验证Cookie?
创始人
2024-09-17 10:30:33
0

在ASP.net CORE 3框架中,要更新身份验证Cookie,可以使用以下代码:

await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddDays(7) });

其中,CookieAuthenticationDefaults.AuthenticationScheme是身份验证方案的名称,principal是包含用户标识信息的ClaimsPrincipal对象。

首先,使用SignOutAsync方法注销当前用户的身份验证Cookie。然后,使用SignInAsync方法重新创建并签署身份验证Cookie,并将其添加到响应中。在此处,我们传递一个IsPersistent属性,以指示Cookie是否应该保持持久性,并且还可以设置过期时间。

完整的代码示例:

[HttpPost]
public async Task Login(LoginViewModel model)
{
    if (ModelState.IsValid)
    {
        // authenticate user
        var user = await _userManager.FindByEmailAsync(model.Email);

        if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
        {
            // create claims principal
            var principal = await _claimsPrincipalFactory.CreateAsync(user);

            // sign in user
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTime.UtcNow.AddDays(7) });

            return RedirectToAction("Index", "Home");
        }
    }

    // return error
    ModelState.AddModelError("", "Invalid email or password");
    return View(model);
}

相关内容

热门资讯

透视开挂!wpk插件,wpk俱... 透视开挂!wpk插件,wpk俱乐部有没有辅助(透视)果然是有技巧(哔哩哔哩)1)免费钻石:进一步探索...
相较于以往!德州局怎么透视,微... 相较于以往!德州局怎么透视,微乐自建房透视,专业脚本(有挂神器)-哔哩哔哩1、每一步都需要思考,不同...
脚本教你!aapoker辅助软... 脚本教你!aapoker辅助软件合法吗,aapoker辅助插件工具(透视)总是真的有插件(哔哩哔哩)...
做出回应!wepoker私人局... 做出回应!wepoker私人局俱乐部辅助,微信小程序辅助多少钱,揭露透视(有挂技巧)-哔哩哔哩wep...
透视总结!xpoker辅助神器... 透视总结!xpoker辅助神器,微乐麻将脚本透视,详情脚本(有挂教学)-哔哩哔哩1、xpoker辅助...
透视推荐!德普之星辅助工具如何... 透视推荐!德普之星辅助工具如何打开,德普之星透视辅助软件激活码(透视)确实真的有技巧(哔哩哔哩)脚本...
透视攻略!哈糖大菠萝能开挂吗,... 透视攻略!哈糖大菠萝能开挂吗,微乐游戏小程序脚本,有挂脚本(详细教程)-哔哩哔哩1、玩家可以在哈糖大...
脚本了解!aapoker怎么控... 脚本了解!aapoker怎么控制牌,aapoker透视插件(透视)一贯有方法(哔哩哔哩)1、下载好脚...
透视线上!wepoker养号规... 透视线上!wepoker养号规律,微乐河南家乡麻将辅助脚本,解谜透视(有挂方针)-哔哩哔哩1、透视线...
透视揭幕!wepoker透视版... 透视揭幕!wepoker透视版下载,wepoker轻量版有透视吗(透视)好像是真的挂(哔哩哔哩)1、...