【问题标题】:AspNet Core CookieAuthentication with injected SessionStore带有注入 SessionStore 的 AspNet Core CookieAuthentication
【发布时间】:2017-08-28 07:48:42
【问题描述】:

在将 ASPNetCore 1.1 项目迁移到 ASPNetCore 2.0 期间,我们偶然发现了 Cookie-AuthN 及其SessionStore 的问题。

ASP.NET Core 1 允许我们做这样的事情:

public void ConfigureServices(...) {
    Services.AddDistributedSqlServerCache(...);
    Services.AddSingleton<DistributedCookieSessionStore>(); /// SQL based store
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerfactory) {
    var cookieOptions = app.ApplicationServices.GetRequiredService<IOptions<CookieAuthenticationOptions>>().Value;
    cookieOptions.SessionStore = app.ApplicationServices.GetRequiredService<DistributedCookieSessionStore>();

    app.UseCookieAuthentication(cookieOptions);
}

杂乱无章,但尽其所能。

现在使用 ASP.NET Core 2 app.UseAuthentication() 没有允许修改选项的签名,并且我无法使用 DI 来获取会话存储。

【问题讨论】:

    标签: asp.net-core-2.0


    【解决方案1】:

    经过长时间的搜索,我遇到了这个讨论https://github.com/aspnet/Security/issues/1338,他们提到了IPostConfigureOptions 接口。我把它放在一起,这对我有用:

    1) 实现接口IPostConfigureOptions&lt;CookieAuthenticationOptions&gt;

    public class PostConfigureCookieAuthenticationOptions : IPostConfigureOptions<CookieAuthenticationOptions>
    {
        private readonly ITicketStore _ticketStore;
    
        public PostConfigureCookieAuthenticationOptions(ITicketStore ticketStore)
        {
            _ticketStore = ticketStore;
        }
    
        public void PostConfigure(string name, CookieAuthenticationOptions options)
        {
            options.SessionStore = _ticketStore;
        }
    }
    

    2) 在Startup.ConfigureServices方法中将此实现注册到容器中

    services.AddSingleton&lt;IPostConfigureOptions&lt;CookieAuthenticationOptions&gt;, PostConfigureCookieAuthenticationOptions&gt;();

    【讨论】:

    • 非常感谢您!重大帮助!
    • 我希望我能投票赞成 10 倍。这是在本地 IDP 上使用 OIDC 保护资源时,我可以让 SessionStore 与 ASP.NET Identity 2.x + IdentityServer 一起使用的唯一方法。谢谢!
    • @pvasek services.AddSingleton, PostConfigureCookieAuthenticationOptions>(); ==> 我认为这里不应该使用 AddSingleton
    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    相关资源
    最近更新 更多