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

Blazor Server与Web API同项目部署后Windows认证遇未授权错误

问题描述

我在同一项目中集成了Blazor Server与Web API,本地笔记本电脑上调用Web API一切正常,但部署到Web服务器后,使用Windows认证时出现未授权错误。用Postman调用服务器上的Web API也返回未授权结果。

相关代码

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme).AddNegotiate();
builder.Services.AddAuthorization(o => { o.FallbackPolicy = o.DefaultPolicy; });

var config = builder.Configuration;
builder.Services.AddDbContext<AppCtx>(o => o.UseSqlServer(config.GetConnectionString("APP")));

builder.Services.AddMvc();
builder.Services.AddServerSideBlazor();

string baseUrl = config.GetValue<string>("AppSettings:BaseUrl");
builder.Services.AddHttpClient<IAdminService, AdminService>(client =>
{
    client.BaseAddress = new Uri(baseUrl);
})
.ConfigurePrimaryHttpMessageHandler(() =>
    new HttpClientHandler()
    {
        UseDefaultCredentials = true,
        Credentials = System.Net.CredentialCache.DefaultCredentials,
        AllowAutoRedirect = true
    });

var app = builder.Build();

string pathBase = config.GetValue<string>("AppSettings:PathBase");
app.UsePathBase(pathBase);

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/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.UseStatusCodePages();
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

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

app.MapControllers();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

AdminController.cs

[AllowAnonymous]
[ApiController]
[Route("[controller]/[action]")]
public class AdminController : ControllerBase
{
    private readonly AppCtx appCtx;

    public AdminController(AppCtx appCtx)
    {
        this.appCtx = appCtx;
    }

    public async Task<IEnumerable<LocationDto>> Locations(string locs)
    {
        var prm = new SqlParameter("@locs", SqlDbType.VarChar, 1024);
        prm.Value = locs;

        string sSql = "EXEC [dbo].[uspLW300_Offices] @locs";
        return await appCtx.SqlQueryAsync<LocationDto>(sSql, prm);
    }
}

错误信息

浏览器开发者工具错误

浏览器请求错误
浏览器未授权错误详情

Postman错误

Postman未授权错误

解决方案
  1. 检查IIS站点认证配置

    • 确保部署项目的IIS站点已启用Windows认证,禁用匿名认证(全局认证策略可能覆盖[AllowAnonymous]的局部设置)。
    • 验证应用程序池身份权限:若使用域账户,需确认该账户拥有访问API和数据库的权限;若用内置账户,检查是否具备足够的资源访问权限。
  2. 修正HttpClient凭据配置

    • 代码中同时设置UseDefaultCredentials = true和Credentials = DefaultCredentials会导致冲突,保留其中一项即可,推荐仅保留UseDefaultCredentials = true:
      .ConfigurePrimaryHttpMessageHandler(() =>
          new HttpClientHandler()
          {
              UseDefaultCredentials = true,
              AllowAutoRedirect = true
          });
      
  3. 验证路径配置正确性

    • 确认服务器上AppSettings:PathBase和AppSettings:BaseUrl的配置与实际站点路径完全匹配,避免因路径不匹配导致认证上下文丢失。
  4. 排查Kerberos/NTLM认证约束

    • 若服务器与客户端不在同一域,需启用NTLM认证;若使用Kerberos,要确保服务主体名称(SPN)已正确注册,避免双跳权限问题。
    • 若Blazor Server与API在同一服务器内,可考虑直接注入服务替代HttpClient调用,减少认证环节的潜在问题。
  5. 调整全局授权策略

    • 当前全局授权策略FallbackPolicy = DefaultPolicy要求用户必须认证,可能覆盖[AllowAnonymous]的作用。可修改授权配置:
      builder.Services.AddAuthorization(o => 
      {
          o.FallbackPolicy = new AuthorizationPolicyBuilder()
              .RequireAuthenticatedUser()
              .Build();
          o.AddPolicy("AllowAnonymousApi", policy => policy.AllowAnonymous());
      });
      
      然后给AdminController添加[Authorize(Policy = "AllowAnonymousApi")],确保匿名访问规则生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 15:00:46