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

本地IIS中SSO正常,同域IIS部署后身份验证异常咨询

解决IIS部署后强制使用Microsoft SSO的方案
  • 禁用IIS的Windows身份验证
    打开IIS管理器找到你的应用,进入「身份验证」面板,直接禁用「Windows身份验证」,只保留「匿名身份验证」——因为OpenID Connect的登录入口需要允许匿名访问,不然IIS会直接触发域身份验证。

  • 修正Program.cs的中间件顺序与配置
    你的现有代码已经添加了Microsoft身份验证,但要确保默认方案明确,且中间件顺序正确。参考修改后的代码:

    var builder = WebApplication.CreateBuilder(args);
    var initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' ') ?? Array.Empty<string>();
    
    // 明确将OpenID Connect设为默认身份验证方案
    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
            .EnableTokenAcquisitionToCallDownstreamApi(initialScopes)
                .AddMicrosoftGraph(builder.Configuration.GetSection("MicrosoftGraph"))
                .AddInMemoryTokenCaches();
    
    // 配置授权策略,确保默认策略生效
    builder.Services.AddAuthorization(options =>
    {
        options.FallbackPolicy = options.DefaultPolicy;
    });
    
    var app = builder.Build();
    
    // 中间件顺序不能乱:身份验证必须在授权之前
    if (!app.Environment.IsDevelopment())
    {
        app.UseExceptionHandler("/Error");
        app.UseHsts();
    }
    
    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();
    
    app.UseAuthentication(); // 先处理身份验证
    app.UseAuthorization();  // 再处理授权
    
    app.MapRazorPages();
    app.MapControllers();
    
    app.Run();
    
  • 清理web.config中的自动配置
    发布到IIS后,web.config可能被自动添加Windows身份验证的配置,手动修改:
    在<system.webServer>节点下添加或修改身份验证配置:

    <system.webServer>
      <security>
        <authentication>
          <anonymousAuthentication enabled="true" />
          <windowsAuthentication enabled="false" />
        </authentication>
      </security>
    </system.webServer>
    

    同时检查<system.web>节点,如果有<authentication mode="Windows"/>,改成<authentication mode="None"/>

  • 确认Azure AD应用的重定向URI
    登录Azure门户,找到你的应用注册,添加生产环境的重定向URI,格式是https://你的IIS服务器域名/signin-oidc,类型选「Web」,确保和本地开发时的逻辑一致。

  • 验证Graph API调用的令牌类型
    确保创建SharePoint文件夹时用的是用户委托令牌,也就是通过用户登录后的上下文获取的令牌,而不是应用自身的权限令牌。你的现有代码中EnableTokenAcquisitionToCallDownstreamApi已经配置了用户令牌获取,只要调用Graph时用注入的GraphServiceClient即可,它会自动使用用户的令牌。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 05:58:28