简体   繁体   English

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

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

I'm using ASP.NET Core MVC with CookieAuthentication.我正在使用带有 CookieAuthentication 的 ASP.NET Core MVC。 Is there a way I can sign all users out at once?有没有办法让所有用户一次注销? I tried resetting IIS - didn't work.我尝试重置 IIS - 没有用。 I tried deleting all the users' sessions (I'm using a database for session storage) - didn't work.我尝试删除所有用户的会话(我使用数据库进行会话存储) - 没有用。

Any ideas?有什么想法吗?

With CookieAuthentication, the cookie is simply an encrypted string containing the user's name, roles, and auxilliary data.使用 CookieAuthentication,cookie 只是一个包含用户名、角色和辅助数据的加密字符串。 In short, it identifies the user , not the session.简而言之,它标识的是用户,而不是会话。 Killing sessions does not invalidate the cookie.终止会话不会使 cookie 失效。

That being said, you can stuff a session identifier or other token in the cookie's auxiliary data, and then validate that during the authentication process.话虽如此,您可以在 cookie 的辅助数据中填充会话标识符或其他令牌,然后在身份验证过程中对其进行验证。 An example of someone trying to this can be found here .可以在此处找到某人尝试此操作的示例。

Another option is instead of invalidating sessions you can temporarily disable users in your user repository.另一种选择是,您可以暂时禁用用户存储库中的用户,而不是使会话无效。 Here is an example using ASPNET Identity 2.0. 下面是一个使用 ASPNET Identity 2.0 的示例。

A third (nuclear) option is to change the machine key on all web servers, which will render any old forms authentication cookies unreadable, forcing all users to sign on again.第三个(核心)选项是更改所有 Web 服务器上的机器密钥,这将使任何旧表单身份验证 cookie 不可读,迫使所有用户再次登录。

You can use CookieAuthenticationOptions.SessionStore Property, to store identity information in server side so you can clear it all when you need.您可以使用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);
    }
}

it's very simple.这很简单。 change the login cookie name更改登录cookie名称

in startup.cs, change the default name to anything.在 startup.cs 中,将默认名称更改为任何内容。

 options.Cookie.Name = "NewName";

Complete Example:完整示例:

  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