How can we remove specific user's session in ServiceStack?

房东的猫 提交于 2019-12-14 01:09:00

问题


Admin can disable or suspend user's entrance.

We can check "is user disabled" in "user login". ("Checking Db for each request" is not good option)

So we want to remove user's session when admin disables it's account.

How can we achieve it?


回答1:


If you know or have kept the sessionId you can remove a session from the cache with:

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

But ServiceStack doesn't keep a map of all User's Session ids itself. One way to avoid DB lookups on each request is when disabling the account keep a record of the disabled User Ids which you can later validate in a global Request Filter to ensure the user isn't locked.

Best way to store the locked user ids is in the cache that way the visibility and lifetime of the locked user ids is in the same cache storing the sessions. You can use a custom cache key to record locked user ids, e.g:

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 remove the locked users sessions the next time they try to access ServiceStack, forcing them to login again at which point they will notice they've been locked out.

A new RemoveSession API was added in this commit which makes this a little nicer (from v4.0.34+):

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


来源:https://stackoverflow.com/questions/13159891/how-can-we-remove-specific-users-session-in-servicestack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!