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

我错过了什么?

4

2 回答 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

于 2017-08-19T21:26:34.123 回答
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)解决了这个问题。

于 2017-08-25T18:19:36.333 回答