【问题标题】:Recommended approach for handling non-authenticated sessions on ServiceStack [closed]在 ServiceStack 上处理非身份验证会话的推荐方法 [关闭]
【发布时间】:2017-08-30 21:28:11
【问题描述】:

我有一个 MVC 应用程序,为所有具有购物篮功能的 BLL 集成了 SS。我希望匿名用户能够添加到购物篮,然后在他们返回时继续购物,购物篮的详细信息完好无损 - 所以我觉得在 redis 中使用 ss-pid 作为 sessionId 是最好的方法。

有人可以确认我是否正确解决了这个问题,如果是,我该如何启用此功能? (反正我看不到默认使用 ss-pid)。

谢谢。

【问题讨论】:

    标签: c# asp.net-mvc cookies servicestack


    【解决方案1】:

    如果您想使用会话 Cookie 来存储未经身份验证的用户信息,那么您需要设置:

    Plugins.Add(new AuthFeature(...) {
        GenerateNewSessionCookiesOnAuthentication = false
    });
    

    因此,当用户进行身份验证时,它会保留现有的 Cookie,否则您需要设置和使用自己的 Cookie,这些 Cookie 在用户登录时不会受到影响。

    SessionBag 是一个很好的解决方案,它使用用户会话 Cookie 来存储未经身份验证的用户的会话数据,例如您可以使用以下内容填充自定义 POCO:

    var unAuthInfo = SessionBag.Get<UnAuthInfo>() ?? new UnAuthInfo();
    unAuthInfo.CustomInfo = request.CustomInfo;
    SessionBag.Set(unAuthInfo);
    

    然后,当用户进行身份验证时,从 Session Bag 中检索信息并使用 OnAuthenticated() 事件将其添加到您的 Typed Custom UserSession 中,例如:

    public class CustomUserSession : AuthUserSession
    {
        [DataMember]
        public string CustomInfo { get; set; }
    
        public override void OnAuthenticated(IServiceBase authService, IAuthSession session, 
            IAuthTokens tokens, Dictionary<string, string> authInfo)
        {
            var unAuthInfo = authService.GetSessionBag().Get<UnAuthInfo>();
    
            if (unAuthInfo != null)
                this.CustomInfo = unAuthInfo.CustomInfo;
        }
    }
    

    【讨论】:

    • 假设我想使用SS会话cookie,有没有办法让匿名用户默认使用ss-pid会话ID?
    • @richardwhatever 要么将 ss-opt Session Cookie 更改为 ss-opt=perm,要么您可以使用 var sessionBag = new SessionFactory.SessionCacheClient(Cache, Request.GetPermanentSessionId()); 强制它
    • 当我设置 ss-opt=perm 时,初始(新用户,无 cookie)请求似乎还不够早,因此会话是在 redis 中使用 ss- ID。然后响应包含 ss-opt=perm,然后在下一个请求中,这次使用 ss-pid 创建一个新的匿名用户会话,从而在缓存中留下 ss-id 会话冗余。如何确保立即使用 ss-pid 存储新的用户请求?
    • 添加一个 Glogal 请求过滤器以始终检查是否ss-opt=perm,如果没有则调用IRequest.SessionOptionsKey("perm")
    • 在我的 CustomUserSession 的 OnCreated(IRequest httpReq) 方法中保存会话之前,我通过添加以下代码来实现这一点:httpReq.AddSessionOptions(SessionOptions.Permanent); httpReq.GenerateNewSessionCookies(this); 这然后强制第一个请求使用 ss-pid,没有检查所有未来请求的开销。你觉得这是一个好的解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-15
    • 2018-06-12
    • 2010-10-25
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    相关资源
    最近更新 更多