Asp.net-Core-2.0
帶有註入 SessionStore 的 AspNet Core CookieAuthentication
在將 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介面。我把它放在一起,這對我有用:
- 實現介面
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>();