我正在使用带有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);
});