Asp.net-Core-2.0

帶有註入 SessionStore 的 AspNet Core CookieAuthentication

  • December 3, 2018

在將 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 來獲取會話儲存。

經過長時間的搜尋,我遇到了這個討論https://github.com/aspnet/Security/issues/1338他們提到了IPostConfigureOptions介面。我把它放在一起,這對我有用:

  1. 實現介面IPostConfigureOptions<CookieAuthenticationOptions>
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;
   }
}

Startup.ConfigureServices2) 在方法中將此實現註冊到容器中

services.AddSingleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>();

引用自:https://stackoverflow.com/questions/45914143