Refresh user cookie ticket in ASP.Net Core Identity

后端 未结 2 755
日久生厌
日久生厌 2020-12-05 12:11

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.

The client is authenticated and a

2条回答
  •  一生所求
    2020-12-05 12:31

    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>();
            var signInManager = context.RequestServices
                .GetRequiredService>();
    
            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 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 Validate()
    {
        // your normal controller code
    }
    

提交回复
热议问题