InvalidOperationException:没有配置IAuthenticationSignInHandler来处理该方案的登录:MyCookieAuthenticationScheme

时间:2017-08-19 21:18:53

标签: c# .net-core-2.0 asp.net-core-mvc-2.0

我正在尝试按照here的说明将Cookie身份验证添加到我的网站。

到目前为止,我添加了以下内容:

  

在。的Configure方法中调用UseAuthentication方法   Startup.cs文件:

app.UseAuthentication();
  

在中调用AddAuthentication和AddCookie方法   Startup.cs文件的ConfigureServices方法:

services.AddAuthentication("MyCookieAuthenticationScheme")
    .AddCookie(options => {
    options.AccessDeniedPath = "/Account/Forbidden/";
    options.LoginPath = "/Account/Unauthorized/";
});

在我的登录代码中,我有

await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal);

principleClaimsPrincipal

当我登录我的网站并拨打上面的一行时,我收到错误:

  

InvalidOperationException:没有IAuthenticationSignInHandler   配置为处理该方案的登录:   MyCookieAuthenticationScheme

我错过了什么?

2 个答案:

答案 0 :(得分:26)

您说您希望默认方案为“MyCookieAuthenticationScheme”(这是AddAuthentication的第一个参数),但您没有添加具有该名称的身份验证处理程序。当您调用AddCookies时,您添加了具有“Cookies”方案的处理程序(这是默认设置)。

您需要将代码更改为:

services.AddAuthentication("MyCookieAuthenticationScheme")
    .AddCookie("MyCookieAuthenticationScheme", options => 
    {
        options.AccessDeniedPath = "/Account/Forbidden/";
        options.LoginPath = "/Account/Unauthorized/";
    });

请参阅此文章以更好地理解原语:

https://digitalmccullough.com/posts/aspnetcore-auth-system-demystified.html

答案 1 :(得分:0)

尝试更改通话地点services.AddAuthentication(这有助于我。

public IServiceProvider ConfigureServices(IServiceCollection services)
{
    ...
    var builder = new ContainerBuilder();
    builder.RegisterModule(new HowResolveDependencies());

    services.AddTransient<IExceptionHandler, ExceptionToResponseWriter>();

    builder.Populate(services);

    services.AddAuthentication(AuthConsts.MainAuthScheme)
                 .AddCookie(
    ...
}

在我的项目中,在services.AddAuthentication之前放置builder.Populate(services)解决了问题。