3

我正在尝试使用 Blazor(服务器端和 .net core 3.0 preview-6)进行 AD 身份验证。

当我添加时,@attribute [Authorize(Roles = "DomainUsers")]我收到以下错误。

如果我更改为 Policy,我会收到同样的错误。但是,如果我只使用[Authorize]我不会收到错误。

当我单击菜单中的链接时会发生这种情况。如果我在浏览器中编写直接路径,我会按预期工作。

public Startup(IConfiguration config)
    {
        Configuration = config;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddNewtonsoftJson();
        services.AddRazorPages();
        services.AddServerSideBlazor();
        services.AddHttpContextAccessor();
        services.AddAuthentication();
        services.AddAuthorization();

        services.AddHttpClient();

        var appDB = Configuration.GetConnectionString("AppDB");
        services.Configure<CtApiSettings>(Configuration.GetSection("CtApiSettings"));

        services.AddDbContext<ApplicationContext>(o => o.UseSqlServer(appDB, builder =>
        {
            builder.EnableRetryOnFailure(5, TimeSpan.FromSeconds(10), null);
        }));


        services.AddToaster(config =>
        {
            config.PositionClass = Defaults.Classes.Position.TopFullWidth;
            config.PreventDuplicates = false;
            config.NewestOnTop = false;
            config.ShowTransitionDuration = 500;
            config.VisibleStateDuration = 5000;
            config.HideTransitionDuration = 500;
        });

        // Setup HttpClient for server side in a client side compatible fashion
        services.AddScoped<HttpClient>(s =>
        {
            // Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
            var uriHelper = s.GetRequiredService<IUriHelper>();
            return new HttpClient
            {
                BaseAddress = new Uri(uriHelper.GetBaseUri())
            };
        });

        ActiveDirectoryModel adm = new ActiveDirectoryModel();
        Configuration.GetSection("AD").Bind(adm);
        services.Configure<ActiveDirectoryModel>(Configuration.GetSection("AD"));

        services.AddScoped<ExcelExportService>();
        services.AddScoped<IAreaService, AreaService>();
        services.AddScoped<IUserProvider>(x => new UserProvider(adm));
        services.AddScoped<IAdminService, AdminService>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            //endpoints.MapRazorPages();
            //endpoints.MapControllers();
            endpoints.MapBlazorHub();
            endpoints.MapFallbackToPage("/_Host");
        });
    }

错误:System.ObjectDisposedException:安全句柄已关闭。对象名称:'SafeHandle'。在 System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean&success) 在 System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean&success) 在 Interop.Advapi32.GetTokenInformation(SafeAccessTokenHandle TokenHandle, UInt32 TokenInformationClass, SafeLocalAllocHandle TokenInformation, UInt32 TokenInformationLength, ) 在 System.Security.Principal.WindowsIdentity.GetTokenInformation(SafeAccessTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, Boolean nullOnInvalidParam) 在 System.Security.Principal.WindowsIdentity.get_User() 在 System.Security.Principal.WindowsIdentity.b__51_0() 在 System.Security。 Principal.WindowsIdentity。
在 System.Security.Claims.ClaimsIdentity.HasClaim(String type, String value) 在 System.Security.Claims.ClaimsPrincipal.IsInRole(String role) 在 System.Security.Principal.WindowsPrincipal.IsInRole(String role) 在 Microsoft.AspNetCore。 Authorization.Infrastructure.RolesAuthorizationRequirement.<>c__DisplayClass4_0.b__0(String r) at System.Linq.Enumerable.Any[TSource](IEnumerable 1 source, Func2 predicate) at Microsoft.AspNetCore.Authorization.Infrastructure.RolesAuthorizationRequirement.HandleRequirementAsync(AuthorizationHandlerContext context, RolesAuthorizationRequirement 要求)在 Microsoft.AspNetCore.Authorization.AuthorizationHandler1.HandleAsync(AuthorizationHandlerContext context) at Microsoft.AspNetCore.Authorization.Infrastructure.PassThroughAuthorizationHandler.HandleAsync(AuthorizationHandlerContext context) at Microsoft.AspNetCore.Authorization.DefaultAuthorizationService.AuthorizeAsync(ClaimsPrincipal user, Object resource, IEnumerable1 个要求)在 Microsoft.AspNetCore.Components.ComponentBase.CallStateHasChangedOnAsyncCompletion(任务任务)在 Microsoft.AspNetCore.Components.AuthorizeViewCore.OnParametersSetAsync() 的 Microsoft.AspNetCore.Components.AuthorizeViewCore.IsAuthorizedAsync(ClaimsPrincipal user)。 ComponentBase.RunInitAndSetParametersAsync()

4

2 回答 2

1

根据github 上的问题跟踪器:

目前,内置的内部默认 FixedAuthenticationStateProvider 假定身份验证状态在电路的生命周期内是固定的,正如其名称所暗示的那样。但是,这对于 Windows 身份验证来说是不够的,因为 WindowsPrincipal 已连接到底层操作系统服务,并且如果原始 HTTP 请求已完成,则无法继续使用。如果主体已被处置,则尝试调用诸如 IsInRole 之类的东西会抛出

该修复已合并到 master 并将与 asp.net core 3.0.0-preview8 一起发布

更新:似乎已解决,请参阅此处升级到 preview8 并修复重大更改。

于 2019-08-02T11:43:11.370 回答
0

我有同样的问题 - 带有 .Net Core 3.0-preview 6 的 Blazor 应用程序。

我正在使用自定义AuthorizationHandler和身份框架。HandleRequirementAsync尝试使用 读取当前用户的名称时会在内部引发错误context.User.Identity.Name

于 2019-07-02T15:02:54.627 回答