服务器端缓存声称与Owin认证 [英] Server side claims caching with Owin Authentication

查看:230
本文介绍了服务器端缓存声称与Owin认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个习惯用 FormsAuthentication ,和前一阵子我切换它使用 IdentityModel 应用程序从 WindowsIdentityFramework ,这样我可以受益于基础的认证要求,但它是相当丑陋的使用和实施。所以,现在我在看 OwinAuthentication

我在看 OwinAuthentication Asp.Net身份框架。但 Asp.Net身份框架的目前唯一实现使用 EntityModel 和我使用 NHibernate的。所以现在我期待尝试绕过 Asp.Net身份,只使用 Owin认证直接。我终于能够得到使用从提示工作登陆<一个href=\"http://stackoverflow.com/questions/18885569/how-do-i-ignore-the-identity-framework-magic-and-just-use-the-owin-auth-middlewa/18923770#18923770\">How做我忽略了身份框架魔术和只使用OWIN AUTH中间件获得索赔我求?,但现在我的饼干拿着号称是相当大的。当我使用了 IdentityModel 我能够使用高速缓存服务器和饼干的索赔刚刚举行的缓存信息的简单令牌服务器端缓存机制。是否有 OwinAuthentication 类似的功能,否则我就必须实现它自己?

我希望我会在这些船只之一...


  1. 的Cookie留为3KB,哦这是一个有点大。

  2. Owin启用类似于 IdentityModel 的SessionCaching功能,我不知道。

  3. 写我自己的实现缓存的信息导致cookie来膨胀,看看我是否能在应用程序启动时把它挂在我配置 Owin

  4. 我做的这一切都错了,那里是我没有想到的办法,否则我在滥用 Owin

    的东西

     公共类OwinConfiguration
    {
        公共无效配置(IAppBuilder应用程序)
        {
            app.UseCookieAuthentication(新CookieAuthenticationOptions
            {
                AuthenticationType =应用程序,
                AuthenticationMode = AuthenticationMode.Active,
                CookieHttpOnly = TRUE,
                CookieName =应用程序,
                ExpireTimeSpan = TimeSpan.FromMinutes(30),
                LOGINPATH =/登录
                LogoutPath =/注销,
                ReturnUrlParameter =RETURNURL
                SlidingExpiration = TRUE,
                供应商=新CookieAuthenticationProvider()
                {
                    OnValidateIdentity =异步上下文=&GT;
                    {
                        //这里处理自定义缓存?
                    }
                }
                // CookieName = CookieAuthenticationDefaults.Cookie preFIX + ExternalAuthentication.ExternalCookieName,
                // ExpireTimeSpan = TimeSpan.FromMinutes(5),
            });
        }
    }


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

 提供程序=新CookieAuthenticationProvider()
{
    OnValidateIdentity =异步上下文=&GT;
    {
        变种用户id = context.Identity.GetUserId(); //只是一个简单的扩展方法来获得使用identity.FindFirst的ID(X =&GT; x.Type == ClaimTypes.NameIdentifier),占空值可能
        如果(用户ID == NULL)回报;
        变种cacheKey =MyApplication_Claim_Roles_+ userId.ToString();
        VAR cachedClaims = System.Web.HttpContext.Current.Cache [cacheKey]为IEnumerable&LT;声明取代;
        如果(cachedClaims == NULL)
        {
            VAR securityService = DependencyResolver.Current.GetService&LT; ISecurityService&GT;(); //我自己的服务从数据库中获取用户的角色
            cachedClaims = securityService.GetRoles(context.Identity.Name)。选择(角色=&gt;新建索赔(ClaimTypes.Role,role.RoleName));
            System.Web.HttpContext.Current.Cache [cacheKey] = cachedClaims;
        }
        context.Identity.AddClaims(cachedClaims);
    }
}


解决方案

OWIN cookie认证的中间件并不支持类似功能会话缓存呢。 #2不是选项。

#3是正确的道路要走。作为Prabu建议,你应该做在你的code以下内容:

OnResponseSignIn:


  • 保存context.Identity与唯一的密钥(GUID)高速缓存

  • 创建嵌入了独特的键的新ClaimsIdentity

  • 新身份置换context.Identity

OnValidateIdentity:


  • 从context.Identity获取唯一键索赔

  • 以独特的键获取缓存的身份

  • 与缓存的身份拨打context.ReplaceIdentity

我要建议你gzip压缩的饼干,但我发现OWIN已经做了,在其TicketSerializer。不是你的选择。

I have an application that used to use FormsAuthentication, and a while ago I switched it to use the IdentityModel from WindowsIdentityFramework so that I could benefit from claims based authentication, but it was rather ugly to use and implement. So now I'm looking at OwinAuthentication.

I'm looking at OwinAuthentication and the Asp.Net Identity framework. But the Asp.Net Identity framework's only implementation at the moment uses EntityModel and I'm using nHibernate. So for now I'm looking to try bypassing Asp.Net Identity and just use the Owin Authentication directly. I was finally able to get a working login using the tips from "How do I ignore the Identity Framework magic and just use the OWIN auth middleware to get the claims I seek?", but now my cookie holding the claims is rather large. When I used the IdentityModel I was able to use a server side caching mechanism that cached the claims on the server and the cookie just held a simple token for the cached information. Is there a similar feature in OwinAuthentication, or would I have to implement it myself?

I expect I'm going to be in one of these boats...

  1. The cookie stays as 3KB, oh well it's a little large.
  2. Enable a feature similar to IdentityModel's SessionCaching in Owin that I don't know about.
  3. Write my own implementation to cache the information causing the cookie to bloat and see if I can hook it up when I configure Owin at application startup.
  4. I'm doing this all wrong and there's an approach I've not thought of or I'm misusing something in 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),
            });
        }
    }
    

UPDATE I was able to get the desired effect using the information Hongye provided and I came up with the below logic...

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);
    }
}

解决方案

OWIN cookie authentication middleware doesn't support session caching like feature yet. #2 is not an options.

#3 is the right way to go. As Prabu suggested, you should do following in your code:

OnResponseSignIn:

  • Save context.Identity in cache with a unique key(GUID)
  • Create a new ClaimsIdentity embedded with the unique key
  • Replace context.Identity with the new identity

OnValidateIdentity:

  • Get the unique key claim from context.Identity
  • Get the cached identity by the unique key
  • Call context.ReplaceIdentity with the cached identity

I was going to suggest you to gzip the cookie, but I found that OWIN already did that in its TicketSerializer. Not an option for you.

这篇关于服务器端缓存声称与Owin认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆