首页 > 解决方案 > Identity Manager SignOutAsync 会话在服务器端仍然有效

问题描述

如果用户保存他们的 cookie,注销,然后将他们的 cookie 导入浏览器,他们就成功登录了。我怎样才能SigninManager杀死他们的会话服务器端呢?我读到了放弃,但它似乎不可用。

这是我的代码:

await _signInManager.SignOutAsync();
HttpContextAccessor httpCon = new HttpContextAccessor();
httpCon.HttpContext.Session.Clear();

标签: c#asp.net-core

解决方案


这是正常的过程。要在注销后使身份 cookie 无效,您可以SecurityStamp通过以下步骤更新并检查它:

  1. CustomCookieAuthenticationEvents

    public class CustomCookieAuthenticationEvents : CookieAuthenticationEvents
    {
        private readonly SignInManager<IdentityUser> _signInManager;
    
        public CustomCookieAuthenticationEvents(SignInManager<IdentityUser> signInManager)
        {
            // Get the database from registered DI services.
            _signInManager = signInManager;
        }
    
        public override async Task ValidatePrincipal(CookieValidatePrincipalContext context)
        {
            var userPrincipal = context.Principal;
    
            var user = await _signInManager.ValidateSecurityStampAsync(userPrincipal);
    
            if (user == null)
            {
                context.RejectPrincipal();
    
                await context.HttpContext.SignOutAsync(
                    IdentityConstants.ApplicationScheme);
            }
        }
    }
    
  2. 注册和配置CustomCookieAuthenticationEvents

    services.AddDefaultIdentity<IdentityUser>()
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();
    services.ConfigureApplicationCookie(options =>
    {
        options.EventsType = typeof(CustomCookieAuthenticationEvents);
    });
    services.AddScoped<CustomCookieAuthenticationEvents>();
    
  3. 登出流程

    await _signInManager.SignOutAsync();
    var user = await _userManager.GetUserAsync(User);
    await _userManager.UpdateSecurityStampAsync(user);
    _logger.LogInformation("User logged out.");
    

推荐阅读