Dot Net Core 2.1 пользовательское удостоверение промежуточного ПО. Не была определена схема authenticationScheme, и не было найдено DefaultForbidScheme - PullRequest
0 голосов
/ 26 июня 2018

Мигрировали наше приложение с .net core 1.1 на 2.1

Контроллеры используют атрибут Authorize:

[Authorize(Roles = "Administrator")]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

В Startup.cs добавьте дополнительное промежуточное программное обеспечение (предоставляются ConfigureServices и Configure):

public void ConfigureServices(IServiceCollection services)
{
    services.AddOptions();
    services.Configure<WebSectionConfigModel>(Configuration.GetSection("Web"));
    services.AddDbContext<MessagingContext>(options => options.UseSqlServer(Configuration.GetConnectionString("messagingConnection")), ServiceLifetime.Transient);
    services.AddTransient(/*...*/);
    services.AddSingleton(/*...*/);

    services.AddSignalR(/* ... */);

   services.AddMvc()
       .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

   services.AddAuthentication(options =>
   {
       options.DefaultAuthenticateScheme = "Anonymous";
       options.DefaultForbidScheme = "Anonymous";
   });

   services.Configure<ForwardedHeadersOptions>(/*...*/);

   services.AddAutoMapper();
}


 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime)
 {
     loggerFactory.AddConsole(LogLevel.Debug);
     loggerFactory.AddDebug();
     loggerFactory.AddNLog();

     app.UseStaticFiles();

     app.UseCors(policyBuilder =>
     {
         /*...*/
     });


     app.UseMiddleware<CustomIdentityMiddleWare>();
     app.UseMiddleware(typeof(ErrorHandlingMiddleware));

     app.UseWebSockets();
     app.UseSignalR(routes =>
     {
         routes.MapHub<MessagesHub>("/messageshub");
     });

     app.UseMvc(Router.GetRouter);
 }

В коде CustomIdentityMiddleWare.cs я создаю пользовательский идентификатор:

public class CustomIdentityMiddleWare
{
    private readonly RequestDelegate _next;

    /* ... ctor and other method ... */

    public async Task Invoke(HttpContext context)
    {
        /* ... */
        ClaimsIdentity claimsIdentity = new CustomIdentity(claims, id, "Custom");

        ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
        context.User = claimsPrincipal;
        await _next(context);

        /* ... */
    }
}

Код удостоверения личности:

public class CustomIdentity : ClaimsIdentity
{
    public Guid Id { get; set; }

    public CustomIdentity(IEnumerable<Claim> claims, Guid Id, string authenticationType) : base(claims, authenticationType)
    {
        this.Id = Id;
    }
}

В .net версии ядра 1.1 все отлично работает. Но в версии 2.1 я начал получать сообщение об ошибке:

2018-06-26 14: 11: 05.6088 | ОШИБКА | Сообщение: Нет аутентификацииСхема была указан, и не найдено DefaultForbidScheme. StackTrace:
в Microsoft.AspNetCore.Authentication.AuthenticationService.ForbidAsync (HttpContext контекст, строковая схема, свойства AuthenticationProperties) в Microsoft.AspNetCore.Mvc.ForbidResult.ExecuteResultAsync (ActionContext контекст) в Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync (IActionResult результат) в Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAlwaysRunResultFilters () в Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync () в Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync ()
в Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke (HttpContext httpContext) в Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke (HttpContext httpContext) в messaging.moex.com_v2.Infrastructure.ErrorHandlingMiddleware.Invoke (HttpContext контекст)

Я понимаю, что должен как-то настроить AddAuthentication, но не знаю точно, как.

Пробовал этот код, но безуспешно:

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = "Anonymous";
    options.DefaultForbidScheme = "Anonymous";
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...