gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 22:02:58 24 4
gpt4 key购买 nike

我正在使用带有 CookieAuthentication 的 ASP.NET Core MVC。有没有办法让所有用户一次注销?我尝试重置 IIS - 没有用。我尝试删除所有用户的 session (我使用数据库进行 session 存储) - 没有用。

有任何想法吗?

最佳答案

您可以使用 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);
}
}

关于asp.net - 如何在 ASP.NET Core cookie 身份验证中注销所有用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44013648/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com