在使用DI的AddCookie()中利用自定义SessionStore

时间:2018-12-28 10:07:42

标签: c# asp.net-core dependency-injection asp.net-core-mvc identity

我目前正在将Identity与自定义SessionStore结合使用,我尝试使用先前通过DI容器注册的IMemoryCache进行设置。

AddCookie()使我可以访问CookieAuthenticationOptions,这使我可以注册提到的SessionStore

 .AddCookie(IdentityConstants.ApplicationScheme, options =>
            {
               // Cookie settings
               options.Cookie.Name = AdminUi.Security.Authorization.COOKIE_NAME;
               options.Cookie.HttpOnly = true;
               options.Cookie.SameSite = SameSiteMode.Strict;
               options.Cookie.SecurePolicy = CookieSecurePolicy.Always;

               options.ExpireTimeSpan = TimeSpan.FromMinutes(AdminUi.Security.COOKIE_EXPIRE_TIME_SPAN_IN_MINUTES);
               options.LoginPath = new PathString(AdminUi.Security.LOGIN_PATH);
               options.AccessDeniedPath = new PathString(AdminUi.Security.ACCESS_DENIED_PATH);
               options.SlidingExpiration = true;
            });

我尝试使用following approach,这应该使我能够通过IServiceScopeFactory工厂访问注册的服务。

为此,我创建了一个类,负责注册SessionStore

public class ConfigureCookieAuthenticationOptions : IConfigureOptions<CookieAuthenticationOptions>
    {
        private readonly IServiceScopeFactory _serviceScopeFactory;
        public ConfigureCookieAuthenticationOptions(IServiceScopeFactory serviceScopeFactory)
        {
            _serviceScopeFactory = serviceScopeFactory;
        }

        public void Configure(CookieAuthenticationOptions options)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                var provider = scope.ServiceProvider;
                var memoryCache = provider.GetRequiredService<IMemoryCache>();
                options.SessionStore = new InMemoryCacheTicketStore(memoryCache);               
            }
        }
    }

然后,我相应地注册了IConfigureOptions<T>实例。

services.AddSingleton<IConfigureOptions<CookieAuthenticationOptions>, ConfigureCookieAuthenticationOptions>();

不幸的是,从未调用过Configure的{​​{1}}方法。

我想念什么?

更新1

我将ConfigureCookieAuthenticationOptions的接口替换为IConfigureOptions<T>,它可以正常工作。知道为什么它只能与IPostConfigureOptions<T>挂钩一起使用吗?

IPostConfigureOptions

0 个答案:

没有答案