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

Pau*_*aul 6 c# authentication asp.net-mvc

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

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

我现在看的两个选项是:

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

    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;
                }
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

在这里缓存示例

你们觉得怎么样?

谢谢

Dar*_*rov 4

实现此目的的一种更MVC 的方法是编写自定义AuthorizeAttribute并在重写的OnAuthorization方法中执行此操作,而不是使用Application_AuthenticateRequest.

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