繁体   English   中英

如何在 ASP.NET Core cookie 身份验证中注销所有用户?

[英]How to logout all users in ASP.NET Core cookie authentication?

我正在使用带有 CookieAuthentication 的 ASP.NET Core MVC。 有没有办法让所有用户一次注销? 我尝试重置 IIS - 没有用。 我尝试删除所有用户的会话(我使用数据库进行会话存储) - 没有用。

有什么想法吗?

使用 CookieAuthentication,cookie 只是一个包含用户名、角色和辅助数据的加密字符串。 简而言之,它标识的是用户,而不是会话。 终止会话不会使 cookie 失效。

话虽如此,您可以在 cookie 的辅助数据中填充会话标识符或其他令牌,然后在身份验证过程中对其进行验证。 可以在此处找到某人尝试此操作的示例。

另一种选择是,您可以暂时禁用用户存储库中的用户,而不是使会话无效。 下面是一个使用 ASPNET Identity 2.0 的示例。

第三个(核心)选项是更改所有 Web 服务器上的机器密钥,这将使任何旧表单身份验证 cookie 不可读,迫使所有用户再次登录。

您可以使用CookieAuthenticationOptions.SessionStore属性,将身份信息存储在服务器端,以便您可以在需要时将其全部清除。

public void ConfigureServices(IServiceCollection services)
{
    MemoryCacheTicketStore memoryCacheTicketStore = new MemoryCacheTicketStore();
    services.AddSingleton<MemoryCacheTicketStore>(memoryCacheTicketStore);

    services.AddAuthentication().AddCookie(cfg =>
    {
        cfg.SessionStore = memoryCacheTicketStore;
    });
}

public class SessionController : Controller
{
    private readonly MemoryCacheTicketStore memoryCacheTicketStore;

    public SessionController(MemoryCacheTicketStore memoryCacheTicketStore)
    {
        this.memoryCacheTicketStore = memoryCacheTicketStore;
    }

    public Task ClearAllSession()
    {
        return memoryCacheTicketStore.ClearAll();
    }
}

public class MemoryCacheTicketStore : ITicketStore
{
    private const string KeyPrefix = "AuthSessionStore-";
    private IMemoryCache _cache;

    public MemoryCacheTicketStore()
    {
        _cache = new MemoryCache(new MemoryCacheOptions());
    }

    public async Task ClearAll()
    {
        _cache.Dispose();
        _cache = new MemoryCache(new MemoryCacheOptions());
    }

    public async Task<string> StoreAsync(AuthenticationTicket ticket)
    {
        var guid = Guid.NewGuid();
        var key = KeyPrefix + guid.ToString();
        await RenewAsync(key, ticket);
        return key;
    }

    public Task RenewAsync(string key, AuthenticationTicket ticket)
    {
        var options = new MemoryCacheEntryOptions();
        var expiresUtc = ticket.Properties.ExpiresUtc;
        if (expiresUtc.HasValue)
        {
            options.SetAbsoluteExpiration(expiresUtc.Value);
        }
        options.SetSlidingExpiration(TimeSpan.FromHours(1)); // TODO: configurable.

        _cache.Set(key, ticket, options);

        return Task.FromResult(0);
    }

    public Task<AuthenticationTicket> RetrieveAsync(string key)
    {
        AuthenticationTicket ticket;
        _cache.TryGetValue(key, out ticket);
        return Task.FromResult(ticket);
    }

    public Task RemoveAsync(string key)
    {
        _cache.Remove(key);
        return Task.FromResult(0);
    }
}

这很简单。 更改登录cookie名称

在 startup.cs 中,将默认名称更改为任何内容。

 options.Cookie.Name = "NewName";

完整示例:

  services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.Name = "NewName"; //<-- Here
                options.Cookie.HttpOnly = true;
              ...
                options.Events = options.Events ?? new CookieAuthenticationEvents();
                var onForbidden = options.Events.OnRedirectToAccessDenied;
                var onUnauthorized = options.Events.OnRedirectToLogin;
                options.Events.OnRedirectToAccessDenied = (context) => OnRedirect(context, onForbidden, HttpStatusCode.Forbidden);
                options.Events.OnRedirectToLogin = (context) => OnRedirect(context, onUnauthorized, HttpStatusCode.Unauthorized);
            });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM