32

我有一个曾经使用过的应用程序,FormsAuthentication不久前我将其切换为使用IdentityModelfromWindowsIdentityFramework以便我可以从基于声明的身份验证中受益,但是使用和实现起来相当难看。所以现在我在看OwinAuthentication

我在看OwinAuthenticationAsp.Net Identity框架。但是该Asp.Net Identity框架目前唯一的实现使用EntityModel并且我正在使用nHibernate. 所以现在我想尝试绕过Asp.Net Identity并直接使用Owin Authentication。我终于能够使用“如何忽略身份框架魔术并仅使用 OWIN auth 中间件来获取我寻求的声明? ”中的提示获得有效登录,但现在我持有声明的 cookie 相当大。当我使用它时,IdentityModel我能够使用服务器端缓存机制来缓存服务器上的声明,并且 cookie 只是为缓存信息保存了一个简单的令牌。中是否有类似的功能OwinAuthentication,还是我必须自己实现?

我希望我会在其中一艘船上...

  1. cookie 保持为 3KB,哦,它有点大。
  2. 启用类似于我不知道IdentityModel的 SessionCaching的功能。Owin
  3. 编写我自己的实现来缓存导致 cookie 膨胀的信息,看看我是否可以Owin在应用程序启动时配置它。
  4. 我做这一切都错了,有一种我没有想到的方法,或者我在Owin.

    public class OwinConfiguration
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Application",
                AuthenticationMode = AuthenticationMode.Active,
                CookieHttpOnly = true,
                CookieName = "Application",
                ExpireTimeSpan = TimeSpan.FromMinutes(30),
                LoginPath = "/Login",
                LogoutPath = "/Logout",
                ReturnUrlParameter="ReturnUrl",
                SlidingExpiration = true,
                Provider = new CookieAuthenticationProvider()
                {
                    OnValidateIdentity = async context =>
                    {
                        //handle custom caching here??
                    }
                }
                //CookieName = CookieAuthenticationDefaults.CookiePrefix + ExternalAuthentication.ExternalCookieName,
                //ExpireTimeSpan = TimeSpan.FromMinutes(5),
            });
        }
    }
    

更新 我能够使用宏业提供的信息获得预期的效果,我想出了以下逻辑......

Provider = new CookieAuthenticationProvider()
{
    OnValidateIdentity = async context =>
    {
        var userId = context.Identity.GetUserId(); //Just a simple extension method to get the ID using identity.FindFirst(x => x.Type == ClaimTypes.NameIdentifier) and account for possible NULLs
        if (userId == null) return;
        var cacheKey = "MyApplication_Claim_Roles_" + userId.ToString();
        var cachedClaims = System.Web.HttpContext.Current.Cache[cacheKey] as IEnumerable<Claim>;
        if (cachedClaims == null)
        {
            var securityService = DependencyResolver.Current.GetService<ISecurityService>(); //My own service to get the user's roles from the database
            cachedClaims = securityService.GetRoles(context.Identity.Name).Select(role => new Claim(ClaimTypes.Role, role.RoleName));
            System.Web.HttpContext.Current.Cache[cacheKey] = cachedClaims;
        }
        context.Identity.AddClaims(cachedClaims);
    }
}
4

3 回答 3

15

OWIN cookie 身份验证中间件尚不支持会话缓存等功能。#2 不是一个选项。

#3 是正确的方法。正如 Prabu 建议的那样,您应该在代码中执行以下操作:

响应登录:

  • 使用唯一键(GUID)将 context.Identity 保存在缓存中
  • 创建一个嵌入了唯一键的新 ClaimsIdentity
  • 将 context.Identity 替换为新的身份

OnValidateIdentity:

  • 从 context.Identity 获取唯一键声明
  • 通过唯一键获取缓存的标识
  • 使用缓存的身份调用 context.ReplaceIdentity

我打算建议你对 cookie 进行 gzip,但我发现 OWIN 已经在它的 TicketSerializer 中这样做了。不是你的选择。

于 2013-10-07T18:05:36.820 回答
8
Provider = new CookieAuthenticationProvider()
{
    OnResponseSignIn = async context =>
    {
        // This is the last chance before the ClaimsIdentity get serialized into a cookie. 
        // You can modify the ClaimsIdentity here and create the mapping here. 
        // This event is invoked one time on sign in. 
    }, 
    OnValidateIdentity = async context => 
    {
        // This method gets invoked for every request after the cookie is converted 
        // into a ClaimsIdentity. Here you can look up your claims from the mapping table. 
    }
}
于 2013-10-05T02:16:54.410 回答
1

您可以实现 IAuthenticationSessionStore 以将 cookie 存储到数据库中。

这是在 redis 中存储 cookie 的示例。

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
SessionStore = new RedisSessionStore(new TicketDataFormat(dataProtector)),
LoginPath = new PathString("/Auth/LogOn"),
LogoutPath = new PathString("/Auth/LogOut"),

});

在此处查看完整示例

于 2016-08-03T06:20:11.040 回答