且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我们如何在 ServiceStack 中删除特定用户的会话?

更新时间:2023-11-27 22:59:52

如果您知道或保留了 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);