Update Custom Cookie Ticket in ASP.NET Core Identity

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

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 update the data in the cookie.

SignInManager has the RefreshSignInAsync refresh RefreshSignInAsync , but does not accept HttpContext.User as a parameter.

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

How to update a cookie?

+5
source share
1 answer
 public static class HttpContextExtenssions { 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 draw it in the action filter

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

Then use it in your controller

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

Source: https://habr.com/ru/post/1263379/


All Articles