在 ASP.Net Core Identity 中刷新用户 cookie 票证 [英] Refresh user cookie ticket in ASP.Net Core Identity

查看:36
本文介绍了在 ASP.Net Core Identity 中刷新用户 cookie 票证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a controller in an ASP.NET Core web application I want to refresh the user and claims in the cookie ticket stored on the client.

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

The client is authenticated and authorized, ASP.NET Core Identity stores this Information in the cookie ticket - now in some Controller actions I want to refresh the data in the cookie.

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

The SignInManager has a function to refresh RefreshSignInAsync, but it does not accept HttpContext.User as parameter.

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

如何刷新 cookie?

How do I refresh the cookie?

推荐答案

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

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

Then use it in your controller

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

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

Or abstract it in an action filter

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

        await next();
    }
}

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

Then use it like this in your controller

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

这篇关于在 ASP.Net Core Identity 中刷新用户 cookie 票证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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