[英]How to logout all users in ASP.NET Core cookie authentication?
我正在使用帶有 CookieAuthentication 的 ASP.NET Core MVC。 有沒有辦法讓所有用戶一次注銷? 我嘗試重置 IIS - 沒有用。 我嘗試刪除所有用戶的會話(我使用數據庫進行會話存儲) - 沒有用。
有什么想法嗎?
您可以使用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.