【问题标题】:ASP.NET MVC built-in membership vs sessionASP.NET MVC 内置成员与会话
【发布时间】:2010-09-26 07:17:20
【问题描述】:

刚刚花了 3 天时间探索会员资格、校长、身份和其他好东西..但仍有一些不清楚的地方。 为什么最好在会话中使用简单存储最小化登录用户对象的方法? 它可以保存角色、权限和其他自定义属性。

为了实现与我会做的 asp.net 形式的身份验证方式相同的事情:

protected void Application_AuthenticateRequest() 
{ 
    HttpCookie cookie = Request.Cookies.Get(FormsAuthentication.FormsCookieName); 
    if (cookie == null) 
        return; 
    bool isPersistent; 
    int webuserid = GetUserId(cookie, out isPersistent); 

    //Lets see if the user exists 
    var webUserRepository = Kernel.Get<IWebUserRepository>(); 

    try 
    { 
        WebUser current = webUserRepository.GetById(webuserid); 

        //Refresh the cookie 
        var formsAuth = Kernel.Get<IFormsAuthService>(); 

        Response.Cookies.Add(formsAuth.GetAuthCookie(current, isPersistent)); 
        Context.User = current; 
    } 
    catch (Exception ex) 
    { 
        //TODO: Logging 
        RemoveAuthCookieAndRedirectToDefaultPage(); 
    } 
} 

private int GetUserId(HttpCookie cookie, out bool isPersistent) 
{ 
    try 
    { 
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value); 
        isPersistent = ticket.IsPersistent; 
        return int.Parse(ticket.UserData); 
    } 
    catch (Exception ex) 
    { 
        //TODO: Logging 

        RemoveAuthCookieAndRedirectToDefaultPage(); 
        isPersistent = false; 
        return -1; 
    } 
}

所以我需要在每个经过身份验证的请求上查询数据库,在使用会话时,我只会在用户登录时执行一次,我知道您可以将角色和其他用户数据存储在票证 cookie 中,但是我认为它不安全,因为攻击者可以修改 cookie 内容、移动它等等。

那么,还有人同意吗?

【问题讨论】:

    标签: asp.net-mvc session membership


    【解决方案1】:

    默认的 InProc Session 状态不是持久的,并且会在您的应用程序池回收时“消失”。

    SqlStore 会话是持久的,但您的数据库服务器上会有额外的负载。

    Cookie 是目前网站的最佳选择,而且可能在很长一段时间内都不会改变。 Cookie 相对安全,只要您加密 Cookie 内容,.net 默认会这样做,您应该没问题。

    注意:.Net 在其默认加密方法方面存在很大的安全漏洞,所以当我说安全时,我的意思是安全并且可能会再次安全。

    http://weblogs.asp.net/scottgu/archive/2010/09/18/important-asp-net-security-vulnerability.aspx

    【讨论】:

    • 值得指出的是,如果您愿意稍微偏离常规,也可以选择上述方法。 Mongo/Memcached 可以很好地处理这种事情。
    • 谢谢,但是考虑一下上面的场景,在每个请求中继续访问数据库以获取用户 obj 并将其分配给上下文是否有意义?
    • @TomerMiz - “在每个请求中继续访问数据库以获取用户 obj 并将其分配给上下文是否有意义”这完全取决于 1. 你需要开发多少时间. 2.您的预期流量是多少。 3. 你有多少 $$$ 用于硬件。 4. 基准测试和测试以确定您的负载水平。据我所知,你甚至还没有开始开发任何东西。等到你获得一些流量,看看什么是明智的表现。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    • 2011-04-16
    • 2015-03-11
    • 1970-01-01
    相关资源
    最近更新 更多