c# - 使用 ASP .NET MVC(缓存、Cookie...)自定义身份验证的最佳选择

标签 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

大家怎么看?

谢谢

最佳答案

一个更MVCish的方法来实现这个是写一个自定义 AuthorizeAttribute并在覆盖 OnAuthorization 中执行此操作方法而不是使用 Application_AuthenticateRequest

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

关于c# - 使用 ASP .NET MVC(缓存、Cookie...)自定义身份验证的最佳选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4214413/

相关文章:

asp.net-mvc - 使用部分GUID作为ID

session - 如何在 Angular JS 应用程序中处理身份验证

c# - 在运行时测试 iOS 版本特定功能的推荐方法

c# - ElementAtOrDefault 的替代方案

C#串口读取错误

c# - asp.net mvc缺少参数时自动抛出404错误

javascript - Kendo Grid 如何创建标题行

c# - 为什么我的 DropDown List Selected Item 每次只显示列表中的第一项?

git - SmartGIT 不要求 ssh key

php - 如何使登录页面 PHP 与 Session 一起工作。