如何从特定会话 Identity Server 4、.Net Core 注销用户?

How to Logout user from a particular session Identity Server 4, .Net Core?

使用 Identity Serve 4 with .Net Core 3.1,剃刀页面。还使用 Cookie 身份验证

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

问题 -

在 Web 应用程序中,约翰登录了 2 次

因此,如果约翰再次尝试在 Firefox 上第 3 次登录而没有从以前的浏览器注销,那么我想从 Chrome 的第一次登录中强制注销约翰。

我可以跟踪会话 table 中的登录情况,包括会话 ID、用户 ID 等。 但是我不知道如何使用会话 ID 从特定会话中注销用户。

请帮忙。

谢谢

既然你说你可以跟踪登录,也许你应该跟踪每个会话并在某处分配一个数字来指示它何时登录(1 代表 Chrome,2 代表边缘,3适用于 Firefox)。

然后每次发出请求时,您都会检查 table 最小的数字是多少(1、2、3 等),如果会话与该数字匹配,则将用户从那个会话。

await HttpContext.SignOutAsync(IdentityServerConstants.DefaultCookieAuthenticationScheme);

由于每个浏览器都会有自己的cookie,可以使用上面的方法。

将某人注销后,下一次登录可以分配 4,如果 2 提出请求,您将注销该客户......

另请参阅:https://github.com/IdentityServer/IdentityServer4/issues/736

I have implemented this. When a user logs in, the session id (IUserSession.GetSessionIdAsync) is manually stored in our database. The previous value of this database field is used to create a logout_token which I send to my clients. You can have look at IdentityServer4.Infrastructure.BackChannelLogoutClient to figure out how to create the token and post. All this assumes you have backchannel logout implemented ofcourse.

ASP.NET Core 提供了一个 ITicketStore 接口,允许您控制存储用户会话。一旦你提供了一个 class 实现这个接口并注册它,它将在创建或验证会话时调用你的 class 然后你可以存储在数据库中,但是你喜欢,包括附加任意元数据,如浏览器身份证等

现在您的数据库中有用户会话,您可以单独查询它们并根据需要在其他逻辑中撤销,包括在登录期间。由于您现在提供了会话数据,因此只需删除记录即可有效地将用户从该会话中注销。请注意,如果您使用任何缓存层来减少存储请求,您还需要删除任何缓存副本。

请注意,这与 IdentityServer 是分开的,并且发生在 ASP.NET Core 本身。

这是一个 good tutorial 帮助我在我的应用程序中实现它的方法。

在 Startup 中注册的示例,其中 PersistentTicketStore 是我的实现:

// Persistent ticket/cookie store to provide durable user sessions
services.AddSingleton<IUserSessionRepository, UserSessionRepository>();
services.AddSingleton<ITicketStore, PersistentTicketStore>();
services.AddOptions<CookieAuthenticationOptions>(CookieAuthenticationDefaults.AuthenticationScheme)
    .Configure<ITicketStore>((options, store) => options.SessionStore = store);

使用结束会话端点

结束会话端点可用于结束会话并触发注销

在登录过程中,您需要捕获从身份验证收到的 id_token 及其所属的用户,并将其存储在某些 dbo.table 上。您可以使用相同的 table 来跟踪用户是否多次登录。

要注销用户或结束会话,您需要在 GET 调用中将保存为名为 id_token_hint 的查询字符串参数的 ID 传递到:

GET /connect/endsession?id_token_hint={id_token}

如需参考,请参阅此处的文档 https://identityserver4.readthedocs.io/en/latest/endpoints/endsession.html#end-session-endpoint