问题描述
在将ASPNetCore 1.1项目迁移到ASPNetCore 2.0的过程中,我们偶然发现Cookie-AuthN及其SessionStore
出现问题.
During migration of an ASPNetCore 1.1 Project to ASPNetCore 2.0, we stumbled upon a Problem with the Cookie-AuthN and its SessionStore
.
ASP.NET Core 1 允许我们执行以下操作:
ASP.NET Core 1 allowed us to do something like that:
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来保留会话存储./p>
Now with ASP.NET Core 2 app.UseAuthentication()
does not have a signature allowing to modify the options, and I am not able to use DI, to get a hold of the session store.
推荐答案
经过长时间的搜索,我遇到了这个讨论 https://github.com/aspnet/Security/issues/1338 ,其中提到了IPostConfigureOptions
界面.我把它们放在一起,对我有用:
After long search I came accross this discussion https://github.com/aspnet/Security/issues/1338 where they mentioned IPostConfigureOptions
interface. I put that together and this works for me:
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;
}
}
2)使用Startup.ConfigureServices
方法将此实现注册到容器中
2) Register this implementation to the container in Startup.ConfigureServices
method
services.AddSingleton<IPostConfigureOptions<CookieAuthenticationOptions>, PostConfigureCookieAuthenticationOptions>();
这篇关于带注入SessionStore的AspNet Core CookieAuthentication的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!