【问题标题】:CookieAuthentication and AspNet Core 2.0 migrationCookie 身份验证和 Asp Net Core 2.0 迁移
【发布时间】:2018-01-27 22:52:25
【问题描述】:

我找不到如何将应用程序从 aspnet core 1.1 迁移到使用 cookie 身份验证的 2.0 的方法。

我已经知道的最有用的资源是:

不幸的是,我仍然卡住了。这是我的做法:
在 Startup.cs ConfigureServices(IServiceCollection services)我有:

services.AddSingleton<IConfigureNamedOptions<CookieAuthenticationOptions>, CookieAuthenticationOptionsSetup>();

及以后:

services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie();

CookieAuthenticationOptionsSetup 类实现IConfigureNamedOptions 并在Configure 方法中设置options.Cookie.Name = "test"。 我尝试手动创建 Name 属性并将其设置为“Cookies”。

如果我尝试在 Startup.cs AddCookie 方法中使用 lambda 表达式更改 cookie 的名称,它会按预期工作。但如果我不这样做,则永远不会使用 CookieAuthenticationOptionsSetup并使用默认的 cookie 名称 (.AspNetCore.Cookies)。

我错过了什么?

【问题讨论】:

  • 请尝试注册您的自定义CookieAuthenticationOptions之后调用AddCookie
  • 我刚刚尝试过。没有成功。

标签: c# asp.net-mvc cookies asp.net-core migration


【解决方案1】:

除了this answer之外,我还必须在实现IConfigureNamedOptions&lt;T&gt;的类中添加Name属性,并在public void Configure(string name, CookieAuthenticationOptions options)方法中设置它。

对于有同样问题的人来说,还有一些额外的注意事项:

要全局应用Authorize 属性,必须添加身份验证方案(以前没有它):

services.AddMvcCore(a =>
{
    var policy = new AuthorizationPolicyBuilder().AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme).RequireAuthenticatedUser().Build();
    a.Filters.Add(new AuthorizeFilter(policy));
});

要在中间件中使用IsAuthenticated属性,必须在注册中间件之前调用app.UseAuthentication()

【讨论】:

    【解决方案2】:

    AddCookie() 默认调用AuthenticationBuilder.AddScheme。从那里,我们可以了解如果您将选项传递给AddCookie 调用,它们将如何理想地注册:

    Services.Configure(authenticationScheme, configureOptions);
    

    让我们来看看Services.Configure 是如何与命名选项一起工作的。服务集合上的ultimately gets registeredIConfigureOptions&lt;CookieAuthenticationOptions&gt;&gt;

    所以我猜想这是稍后通过 DI 解析选项时要查找的确切类型。事实上,that is the exact type 是由 OptionsFactory 请求的 OptionsMonitor 正在使用的 requested by the authentication handler

    所以,tl;dr:您将自定义配置注册为错误的类型。您应该将其注册为IConfigureOptions&lt;&gt;

    services.AddSingleton<IConfigureOptions<CookieAuthenticationOptions>, CookieAuthenticationOptionsSetup>();
    

    当然请注意,您的 CookieAuthenticationOptionsSetup 需要正确实现 IConfigureNamedOptions 并使用您的方案名称 (CookieAuthenticationDefaults.AuthenticationScheme) 响应 Configure 调用。

    【讨论】:

    • 是的,你是对的,我必须实现 IConfigureNamedOptions 但注册为 IConfigureOptions!单独答案中的其他 cmets。
    • @Zygimantas 非常感谢您的额外赏金!这真的没有必要,但这个手势更受欢迎!谢谢你,我很高兴你设法让它工作:)
    【解决方案3】:

    目前还不清楚问题是什么...
    但是,如果您只想设置 cookie 名称(或其他选项)并且真的不需要实现 IConfigureNamedOptions,请尝试以下操作:

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
    {
        options.Cookie.Name = "TestName";
    }
    

    【讨论】:

    • 设置 cookie 名称是一个简化的示例。我使用单独的类,因为配置对于 lambda 来说太复杂了。问题是:为什么 cookie 设置作为一个类没有被注入。
    猜你喜欢
    • 2020-03-09
    • 1970-01-01
    • 2018-02-15
    • 2021-06-15
    • 2018-01-28
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    相关资源
    最近更新 更多