Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Using Identity Serve 4 with .Net Core 3.1, razor pages. Also using Cookie Authentication

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)

Problem -

In a web application John logged-in 2 times

  • 1st Login on Chrome
  • 2nd Login on edge

So, if John again trying to logged-in on 3rd time on Firefox without logout from previous browsers, then I want to logout John from 1st Login on Chrome forcefully.

I can keep the track of logins in a Session table including Session Id, User Id etc. But I don’t know how logout user from a particular session using Session Id.

Please help.

Thanks

like image 667
Ravi Avatar asked Jul 27 '20 07:07

Ravi


People also ask

How to logout from Identity Server?

To signout the user from the server-side client applications via the back-channel spec the IBackChannelLogoutService service can be used. IdentityServer will automatically use this service when your logout page removes the user's authentication cookie via a call to HttpContext. SignOutAsync .


1 Answers

ASP.NET Core provides an ITicketStore interface which allows you to get control of storing user sessions. Once you provide a class implementing this interface and register it, it will call your class when sessions are being created or verified which you can then store in a database however you like, including attaching arbitrary metadata like browser ID etc.

Now that you have user sessions in your database, you can separately query them and revoke as needed in other logic, including during logins. Since you now provide the session data, simply deleting the record effectively logs the user out from that session. Note that if you use any caching layer to reduce the store requests, you'd need to remove any cached copies as well.

Note that this is separate from IdentityServer and happens with ASP.NET Core itself.

This is a good tutorial that helped me implementing this in my app.

A sample of how it looks to register in Startup, where PersistentTicketStore is my implementation:

// 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);
like image 66
Noah Stahl Avatar answered Sep 29 '22 18:09

Noah Stahl