我们如何在 ServiceStack 中删除特定用户的会话? [英] How can we remove specific user's session in ServiceStack?

查看:35
本文介绍了我们如何在 ServiceStack 中删除特定用户的会话?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

管理员可以禁用或暂停用户的入口.

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.

我们怎样才能实现它?

推荐答案

如果您知道或保留了 sessionId,您可以使用以下命令从缓存中删除会话:

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);
}

但是 ServiceStack 本身并没有保留所有用户会话 ID 的映射.避免对每个请求进行数据库查找的一种方法是在禁用帐户时保留禁用用户 ID 的记录,您可以稍后在全局请求过滤器中对其进行验证,以确保用户未被锁定.

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.

存储锁定用户 ID 的最佳方式是在缓存中,这样锁定用户 ID 的可见性和生命周期就在存储会话的同一个缓存中.您可以使用自定义缓存键来记录锁定的用户 ID,例如:

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);
        }
    }
});

这将在他们下次尝试访问 ServiceStack 时删除锁定的用户会话,迫使他们再次登录,此时他们会注意到他们已被锁定.

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.

一个新的 RemoveSession API 被添加到这个提交中,这使得它更好一些(从 v4.0.34+):

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);

这篇关于我们如何在 ServiceStack 中删除特定用户的会话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆