How to delete a specific user session in ServiceStack?

Admin can disable or suspend user login.

We can check the "disconnected user" in the "user login". ("Check Db for each request" is not a good option)

So, we want to delete the user session when admin disconnects his account.

How can we achieve this?

+4
source share
1 answer

If you know or saved sessionId , you can delete the session from the cache with:

 using (var cache = TryResolve<ICacheClient>()) { var sessionKey = SessionFeature.GetSessionKey(sessionId); cache.Remove(sessionKey); } 

But ServiceStack does not save a map of all user session identifiers. One way to avoid database searches for each query is when to disable the account, record disabled User IDs, which can later be checked in the global Query Filter to ensure that the user is not blocked.

The best way to store blocked user IDs is in the cache so that the visibility and lifetime of the blocked user IDs are in the same session storage cache. You can use your own cache key to record blocked user IDs, for example:

 GlobalRequestFilters.Add((req, res, dto) => { var session = req.GetSession(); using (var cache = TryResolve<ICacheClient>()) { if (cache.Get<string>("locked-user:" + session.UserAuthId) != null) { var sessionKey = SessionFeature.GetSessionKey(session.Id); cache.Remove(sessionKey); req.Items.Remove(ServiceExtensions.RequestItemsSessionKey); } } }); 

This will delete the blocked user sessions the next time they try to access the ServiceStack, forcing them to log in again, after which they notice that they are blocked.

A new RemoveSession API has been added to this commit , which makes it a little nicer (from version 4.0.34 +):

 if (cache.Get<string>("locked-user:" + session.UserAuthId) != null) req.RemoveSession(session.Id); 
+5
source

Source: https://habr.com/ru/post/1443241/


All Articles