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

VS2022 .NET9 Blazor项目端口随机变化致Azure MS Graph认证失败

解决.NET 9 Blazor Web App MS Graph认证时随机端口的问题

问题核心

你的Blazor Web App在通过MS Graph向Azure认证时,程序自动传递了随机端口的回调URL,导致Azure认证失败,尽管launchSettings.json已经配置了固定端口。

解决方案

以下是经过验证的解决步骤:

1. 在认证服务中手动指定固定回调URI

在Program.cs的认证配置代码里,强制设置RedirectUri和PostLogoutRedirectUri,覆盖自动检测的端口:

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApp(options =>
    {
        builder.Configuration.Bind("AzureAd", options);
        // 替换为你launchSettings里的固定HTTPS端口(比如44391或7081)
        options.RedirectUri = "https://localhost:44391/signin-oidc";
        options.PostLogoutRedirectUri = "https://localhost:44391/signout-callback-oidc";
    })
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
    .AddInMemoryTokenCaches();

确保这里的端口和你Azure应用注册中添加的重定向URI完全一致。

2. 确认Visual Studio调试配置的一致性

  • 右键项目 → 属性 → 调试选项卡
  • 在"Web服务器设置"区域,确认IIS Express的SSL端口是44391(和launchSettings.json里的sslPort一致)
  • 确保启动时选择的是正确的配置文件(比如你常用的"IIS Express"或"https")

3. 清除本地认证缓存

本地缓存的旧端口信息可能导致问题:

  • 删除用户目录下的缓存文件夹:%USERPROFILE%\.aspnet\DataProtection-Keys
  • 清除浏览器中与Azure认证相关的Cookie和缓存(尤其是login.microsoftonline.com的Cookie)

4. 同步appsettings.json的AzureAd配置

在appsettings.json中明确指定重定向URI,避免自动检测:

"AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "你的租户域名",
    "TenantId": "你的租户ID",
    "ClientId": "你的客户端ID",
    "CallbackPath": "/signin-oidc",
    "RedirectUri": "https://localhost:44391/signin-oidc"
}

额外提示

如果你的Blazor Web App是WebAssembly模式,需要在wwwroot/appsettings.json中同步配置相同的RedirectUri,并确保客户端认证代码中没有动态生成端口的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 05:52:46