Серверная часть Blazor + Kestrel + Windows Auth = Crash - PullRequest
0 голосов
/ 22 октября 2018

Я пытаюсь настроить Windows Auth, используя kesterel на стороне сервера Blazor. У меня есть такая настройка программы: Я использую версию 0.6.0 на стороне сервера Blazor и последний выпуск VS 2017. Использование стандартного блэзораtemnplate.Вы можете видеть, что я включил «Windows Auth» в BuildWebHost «Program.cs». Если я закомментирую строку options.Authentication.AllowAnonymous, все, конечно, будет работать.

Blazor.Web.server

Program.cs

public static void Main(string[] args)
    {
        BuildWebHost(args).Run();            
    }
    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
        .UseHttpSys(
                                    options =>
                                    {
                                        options.Authentication.Schemes =
                                           AuthenticationSchemes.Negotiate | AuthenticationSchemes.NTLM; 
                                        options.Authentication.AllowAnonymous = false;                                          
                                    })
            .UseConfiguration(new ConfigurationBuilder()
                .AddCommandLine(args)
                .Build())
            .UseStartup<Startup>()
            .Build();
}

Startup.cs

public class Startup
            {
            public void ConfigureServices(IServiceCollection services)
            {
            // Since Blazor is running on the server, we can use an application 
            service
            // to read the forecast data.
            services.AddSingleton();
            }
            public void Configure(IBlazorApplicationBuilder app)
            {
            app.AddComponent("app");
            }
        }

Program.cs

public class Program
    { 
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }   

        public static IWebAssemblyHostBuilder CreateHostBuilder(string[] args) =>
            BlazorWebAssemblyHost.CreateDefaultBuilder()
                .UseBlazorStartup<Startup>();
    }

public class HttpContextAccessor
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public HttpContextAccessor(IHttpContextAccessor httpContextAccessor)
        {
               _httpContextAccessor = httpContextAccessor;
        }

        public HttpContext Context => _httpContextAccessor.HttpContext;
    }

Auth.cshtml

using System.Net.Http
@Inject Blazor.Web.App.HttpContextAccessor HttpContext
@page "/two-way-data-binding"

Logged in User: @HttpContext.Context.User.Identity.Name 

Я получаю следующую ошибку при переходе на Auth.cshtml

System.ObjectDisposedException
HResult=0x80131622
Message=Safe handle has been closed
Source=System.Private.CoreLib
StackTrace:
at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
at Interop.Advapi32.GetTokenInformation(SafeAccessTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, UInt32& ReturnLength)
at System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, Boolean nullOnInvalidParam)
at System.Security.Principal.WindowsIdentity.get_User()
at System.Security.Principal.WindowsIdentity.b__46_0()
at System.Security.Principal.WindowsIdentity.<>c__DisplayClass62_0.b__0(Object )
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Security.Principal.WindowsIdentity.RunImpersonatedInternal(SafeAccessTokenHandle token, Action action)
at System.Security.Principal.WindowsIdentity.RunImpersonated(SafeAccessTokenHandle safeAccessTokenHandle, Action action)
at System.Security.Principal.WindowsIdentity.GetName()
at System.Security.Principal.WindowsIdentity.get_Name()
at Cloud.WebUI.App.Pages.TwoWayDataBinding.BuildRenderTree(RenderTreeBuilder builder)
at Microsoft.AspNetCore.Blazor.Rendering.ComponentState.RenderIntoBatch(RenderBatchBuilder batchBuilder, RenderFragment renderFragment)
at Microsoft.AspNetCore.Blazor.Rendering.Renderer.RenderInExistingBatch(RenderQueueEntry renderQueueEntry)
at Microsoft.AspNetCore.Blazor.Rendering.Renderer.ProcessRenderQueue()
at Microsoft.AspNetCore.Blazor.Rendering.Renderer.AddToRenderQueue(Int32 componentId, RenderFragment renderFragment)

Это также создается как «проблема» @ Blazor Issue # 1596

1 Ответ

0 голосов
/ 11 января 2019

Сначала вам не нужен ваш пользовательский класс HttpContextAccessor , так как он не добавляет никакого значения.

Обязательно добавьте следующую строку в ConfigureServices метод сервера Startup.cs

services.AddHttpContextAccessor();

Тогда все в порядке и вы можете использовать HttpContextAccessor в своем приложении Blazor следующим образом:

@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor
User: @HttpContextAccessor.HttpContext.User.Identity.Name

Установите для проверки подлинности Windows значение true в проекте сервера настройки веб-сервера (последняя область в настройках отладки).

Я использую Blazor 0.7.0

...