Asp.Net Identity - Setting CookieDomain at runtime

前端 未结 3 515
小蘑菇
小蘑菇 2021-01-02 05:41

How can I set the CookieDOmain in the CookieAuthenticationOptions at runtime if i want to pull this value from the Request.Url or from some settings stored in my database?

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-02 06:07

    It looks like MK. answer does not allow proper handling of token renewal when using SlidingExpiration option.

    As a workaround, instead of supplying a custom cookie provider, it appears you can supply a custom cookie manager, and define your own methods for adding/removing the cookie.

    To keep it simple in my case, I reuse the default cookie manager under the hood. (I can not extend it, its methods are not overridable.)

    Here is the code I have ended up with:

    using Microsoft.AspNet.Identity;
    using Microsoft.Owin;
    using Microsoft.Owin.Infrastructure;
    using Microsoft.Owin.Security.Cookies;
    using Microsoft.Owin.Security.DataProtection;
    using Owin;
    
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var options = new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                SlidingExpiration = true,
                CookieManager = new CustomCookieManager()
            };
    
            app.UseCookieAuthentication(options);
        }
    }
    
    public class CustomCookieManager : ICookieManager
    {
        private readonly ICookieManager ConcreteManager;
    
        public CustomCookieManager()
        {
            ConcreteManager = new ChunkingCookieManager();
        }
    
        string ICookieManager.GetRequestCookie(IOwinContext context, string key)
        {
            return ConcreteManager.GetRequestCookie(context, key);
        }
    
        void ICookieManager.AppendResponseCookie(IOwinContext context, string key, string value, CookieOptions options)
        {
            SetupDomain(context, options);
            ConcreteManager.AppendResponseCookie(context, key, value, options);
        }
    
        void ICookieManager.DeleteCookie(IOwinContext context, string key, CookieOptions options)
        {
            SetupDomain(context, options);
            ConcreteManager.DeleteCookie(context, key, options);
        }
    
        private void SetupDomain(IOwinContext context, CookieOptions options)
        {
            // custom logic for assigning something to options.Domain
        }
    }
    

提交回复
热议问题