我找不到将应用程序从 aspnet core 1.1 迁移到使用 cookie 身份验证的 2.0 的方法。
我已经知道的最有用的资源是:
- https://learn.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x#cookie-based-authentication
- https://github.com/aspnet/announcements/issues/262
- https://github.com/aspnet/Home/issues/2128 (我自己的问题)
不幸的是,我仍然卡住了。以下是我的做法:
在 Startup.cs ConfigureServices(IServiceCollection services)
我有:
services.AddSingleton<IConfigureNamedOptions<CookieAuthenticationOptions>, CookieAuthenticationOptionsSetup>();
及以后:
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();
CookieAuthenticationOptionsSetup
类(class)工具IConfigureNamedOptions
并设置 options.Cookie.Name = "test"
在Configure
里面方法。
我尝试手动创建 Name 属性并将其设置为“Cookies”。
如果我尝试在 Startup.cs 中使用 lambda 表达式更改 cookie 的名称 AddCookie
方法,它按预期工作。 但如果我不这样做,CookieAuthenticationOptionsSetup
从不使用,并使用默认的 cookie 名称 (.AspNetCore.Cookies)。
我错过了什么?
最佳答案
AddCookie()
默认调用 AuthenticationBuilder.AddScheme
.从那里,我们可以了解如果您将选项传递给 AddCookie
,这些选项将如何理想地注册。调用:
Services.Configure(authenticationScheme, configureOptions);
那么让我们来看看如何Services.Configure
使用命名选项。什么ultimately gets registered在服务集合上是 IConfigureOptions<CookieAuthenticationOptions>>
.
所以我猜这就是稍后通过 DI 解析选项时要查找的确切类型。事实上,that is the exact type OptionsFactory
正在请求OptionsMonitor
正在使用这是requested by the authentication handler .
所以,tl;dr:您将自定义配置注册为错误的类型。您应该将其注册为 IConfigureOptions<>
:
services.AddSingleton<IConfigureOptions<CookieAuthenticationOptions>, CookieAuthenticationOptionsSetup>();
当然要注意你的 CookieAuthenticationOptionsSetup
需要实现 IConfigureNamedOptions
正确回应Configure
使用您的方案名称 ( CookieAuthenticationDefaults.AuthenticationScheme
) 调用。
关于c# - Cookie 身份验证和 Asp Net Core 2.0 迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45770419/