1

我在 https://localhost:5001/ 上运行客户端 blazor wasm,在 https://localhost:44302/ 上运行由http.sys托管的 API 服务器。我已经为 http.sys 设置了 Windows 身份验证,如此处所述https://docs.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-5.0&tabs=visual-studio#httpsys

现在,当在 Blazor wasm 上使用 HttpClient 并使用 [Authorize] 到达控制器或集线器时,我立即获得未经授权。

crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Response status code does not indicate success: 401 (Unauthorized).
System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized) with exception
   at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
   at Microsoft.AspNetCore.Http.Connections.Client.HttpConnection.NegotiateAsync(Uri url, HttpClient httpClient, ILogger logger, CancellationToken cancellationToken)

我想知道为什么没有使用此设置设置凭据的弹出对话框。

相比之下,当我使用 IIS 托管 Blazor wasm 时,它会显示浏览器弹出登录名。

非常感谢您的回答。

4

1 回答 1

0

我解决了。所以基本上问题在于正在发送的请求。

解决方案 1 - 为每个请求手动添加BrowserRequestCredentials.Include

var httpRequest = new HttpRequestMessage();
        
httpRequest.SetBrowserRequestCredentials(BrowserRequestCredentials.Include);

解决方案 2 - 在此处创建委托处理程序参考 https://docs.microsoft.com/en-us/aspnet/core/blazor/fundamentals/signalr?view=aspnetcore-5.0&pivots=webassembly

    public class IncludeRequestCredentialsMessageHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(
            HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include);
            return base.SendAsync(request, cancellationToken);
        }
    }

然后在您的 Program.cs 中将其注册到 DI

builder.Services.AddHttpClient("API", client => client.BaseAddress = new Uri("YOUR URL"))
            .AddHttpMessageHandler(s => new IncludeRequestCredentialsMessageHandler());

builder.Services.AddScoped(sp => sp.GetRequiredService<IHttpClientFactory>()
                .CreateClient("API"));
于 2021-09-30T10:37:30.380 回答