[英]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.