刷新ASP.Net Core Identity中的用户Cookie票证

编程入门 行业动态 更新时间:2024-10-11 01:16:59
本文介绍了刷新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票证中-现在在某些Controller动作中,我想刷新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票证

本文发布于:2023-11-17 09:06:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609562.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:票证   用户   Net   ASP   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!