簡體   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