2017-08-19 14 views
7

Tôi đang cố gắng làm theo các hướng dẫn here để thêm Xác thực Cookie vào trang web của tôi.InvalidOperationException: Không có IAuthenticationSignInHandler được cấu hình để xử lý đăng nhập cho lược đồ: MyCookieAuthenticationScheme

Cho đến nay tôi đã thêm như sau:

Invoke the UseAuthentication method in the Configure method of the Startup.cs file:

app.UseAuthentication(); 

Invoke the AddAuthentication and AddCookie methods in the ConfigureServices method of the Startup.cs file:

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

Trong mã đăng nhập của tôi sau đó tôi có

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

principle là một ClaimsPrincipal.

Khi tôi đăng nhập vào trang web của tôi và gọi dòng ở trên tôi nhận được lỗi:

InvalidOperationException: No IAuthenticationSignInHandler is configured to handle sign in for the scheme: MyCookieAuthenticationScheme

Tôi đã bỏ lỡ gì ra?

Trả lời

20

Bạn đã nói rằng bạn muốn lược đồ mặc định là "MyCookieAuthenticationScheme" (đó là đối số đầu tiên cho AddAuthentication) nhưng bạn không thêm trình xử lý xác thực với tên đó. Khi bạn gọi là AddCookies, bạn đã thêm trình xử lý với lược đồ "Cookie" (đó là mặc định).

Bạn cần thay đổi mã của bạn để:

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

Xem bài viết này để hiểu rõ hơn về nguyên thủy:

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

+0

Cảm ơn bạn! Tôi đã cố gắng tìm ra điều này hầu hết trong ngày. Rất nhiều ví dụ trên mạng nhưng họ bỏ qua trình xử lý xác thực. – Tom

0

Cố gắng thay đổi nơi gọi services.AddAuthentication( này đã giúp tôi.

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(
    ... 
} 

Trong dự án của tôi, đặt services.AddAuthentication trước khi builder.Populate(services) giải quyết được sự cố.

Các vấn đề liên quan