首页 文章

刷新ASP.Net核心标识中的用户cookie票证

提问于
浏览
8

在ASP.NET Core Web应用程序的控制器中,我想刷新存储在客户端上的cookie票证中的用户和声明 .

客户端经过身份验证和授权,ASP.NET Core Identity将此信息存储在cookie票证中 - 现在在某些Controller操作中我想刷新cookie中的数据 .

SignInManager 具有刷新 RefreshSignInAsync 的功能,但它不接受 HttpContext.User 作为参数 .

[HttpPost("[action]")]
[Authorize]
public async Task<IActionResult> Validate()
{
  // todo: update the Client Cookie
  await _signInManager.RefreshSignInAsync(User); // wrong type
}

如何刷新cookie?

1 回答

  • 11
    public static class HttpContextExtensions
    {
        public static async Task RefreshLoginAsync(this HttpContext context)
        {
            if (context.User == null)
                return;
    
            // The example uses base class, IdentityUser, yours may be called 
            // ApplicationUser if you have added any extra fields to the model
            var userManager = context.RequestServices
                .GetRequiredService<UserManager<IdentityUser>>();
            var signInManager = context.RequestServices
                .GetRequiredService<SignInManager<IdentityUser>>();
    
            IdentityUser user = await userManager.GetUserAsync(context.User);
    
            if(signInManager.IsSignedIn(context.User))
            {
                await signInManager.RefreshSignInAsync(user);
            }
        }
    }
    

    然后在您的控制器中使用它

    [HttpPost("[action]")]
    [Authorize]
    public async Task<IActionResult> Validate()
    {
        await HttpContext.RefreshLoginAsync();
    }
    

    或者在动作过滤器中抽象它

    public class RefreshLoginAttribute : ActionFilterAttribute
    {
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            await context.HttpContext.RefreshLoginAsync();
    
            await next();
        }
    }
    

    然后在你的控制器中使用它

    [HttpPost("[action]")]
    [Authorize]
    [RefreshLogin] // or simpler [Authorize, RefreshLogin]
    public async Task<IActionResult> Validate()
    {
        // your normal controller code
    }
    

相关问题