You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server调用Windows认证Web API时出现401未授权错误求助

解决方案

1. 修正Web API的中间件顺序并补全认证中间件

你的Web API代码遗漏了UseAuthentication()中间件,且UseCors的执行顺序错误——CORS中间件必须在认证、授权和路由映射之前运行。修改后的Program.cs如下:

using Microsoft.AspNetCore.Authentication.Negotiate;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

string corsPolicy = "corsPolicy";
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: corsPolicy,
                      policy => {
                          policy.WithOrigins("https://localhost:44389")
                                .AllowAnyMethod()
                                .AllowAnyHeader()
                                .AllowCredentials();
                      });
});

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

builder.Services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});

var app = builder.Build();

app.UseHttpsRedirection();
// 先启用CORS规则
app.UseCors(corsPolicy);
// 添加认证中间件(之前遗漏)
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

app.Run();

2. 配置Blazor Server的HttpClient传递Windows凭据

Blazor Server调用API时,需要让HttpClient携带当前用户的Windows身份凭据。在Blazor项目的Program.cs中注册HttpClient时添加如下配置:

// 替换原有HttpClient注册代码
builder.Services.AddScoped(sp =>
{
    var handler = new HttpClientHandler
    {
        UseDefaultCredentials = true // 关键:传递当前Windows用户凭据
    };
    return new HttpClient(handler)
    {
        BaseAddress = new Uri("https://localhost:44370/")
    };
});

之后在Counter页面中调用API时,可简化路径:

try 
{
    int i = await client.GetFromJsonAsync<int>("weatherforecast/GetA");
}
catch (Exception ex) 
{
    // 可添加错误日志或前端提示逻辑
}

3. 验证IIS Express身份验证配置

确保两个项目的IIS Express都启用Windows身份验证、禁用匿名身份验证:

  • 右键项目 → 属性 → 调试 → 打开launchSettings.json
  • 确认iisSettings节点配置:
"iisSettings": {
  "windowsAuthentication": true,
  "anonymousAuthentication": false,
  // 其他保留配置
}

核心说明

  • Windows身份验证跨域请求必须同时满足:API端CORS允许凭据(AllowCredentials())、客户端请求传递凭据(UseDefaultCredentials = true)。
  • 中间件顺序直接影响功能生效:UseCors必须在UseAuthentication、UseAuthorization、MapControllers之前执行。
  • 确认两个项目的SSL端口与launchSettings.json配置完全一致,避免端口不匹配导致连接问题。

内容的提问来源于stack exchange,提问作者user8149311

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:45:33