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

10

我正在尝试按照这里的说明向我的网站添加Cookie身份验证。

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

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

app.UseAuthentication();

在 Startup.cs 文件的 ConfigureServices 方法中调用 AddAuthentication 和 AddCookie 方法:
services.AddAuthentication("MyCookieAuthenticationScheme")
    .AddCookie(options => {
    options.AccessDeniedPath = "/Account/Forbidden/";
    options.LoginPath = "/Account/Unauthorized/";
});

在我的登录代码中,我有以下内容:
await HttpContext.SignInAsync("MyCookieAuthenticationScheme", principal);

principle 是一个 ClaimsPrincipal

当我登录到我的网站并调用上述代码时,我会收到以下错误:

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

我错过了什么?

2个回答

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


谢谢!我一整天都在试图解决这个问题。虽然有很多例子,但它们都忽略了身份验证处理程序。 - Tom

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)之前解决了这个问题。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接