使用ASP .NET MVC(Cache,Cookie ...)自定义身份验证的最佳选择

时间:2010-11-18 11:50:45

标签: c# asp.net-mvc authentication

我使用身份验证与MVC有点迷失......

我正在寻找在大型电子商务网站中使用的最佳选择,其中性能是首要任务......

我到目前为止看到的两个选项是:

  • 创建 FormsAuthenticationTicket 并将其加密为 Cookie ,就像在此处实施的那样:Cookie implementation
  • 缓存身份验证数据,如:

    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    // Get Forms Identity From Current User
                    FormsIdentity id = FormsIdentity)HttpContext.Current.User.Identity;
                    // Create a custom Principal Instance and assign to Current User (with caching)
                    Customer principal = (Customer)HttpContext.Current.Cache.Get(id.Name);
                    if (principal == null)
                    {
                        // Create and populate your Principal object with the needed data and Roles.
                        principal = MyBusinessLayerSecurityClass.CreatePrincipal(id, id.Name);                            
                        HttpContext.Current.Cache.Add(
                        id.Name,
                        principal,
                        null,
                        System.Web.Caching.Cache.NoAbsoluteExpiration,
                        new TimeSpan(0, 30, 0),
                        System.Web.Caching.CacheItemPriority.Default,
                        null);
                    }
                    HttpContext.Current.User = principal;
                }
            }
        }
    }
    

Caching sample here

你们怎么想?

由于

1 个答案:

答案 0 :(得分:4)

更多 MVCish 实现此目的的方法是编写自定义AuthorizeAttribute并使用覆盖OnAuthorization方法执行此操作,而不是使用Application_AuthenticateRequest

据说我认为你的实施非常好。作为将附加信息存储到缓存中的替代方法,如果此信息当然不是很大,则可以将其存储在身份验证票证的userData部分中。两种方法都是可行的。如果您决定使用缓存,我建议您将其卸载到专用缓存服务器,而不是将其存储在Web服务器的内存中。