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

Swagger UI调用接口时出现CORS错误,求助问题排查

问题描述

我有一个已在Azure中注册的小型WebAPI应用,希望在Swagger UI页面完成登录。目前登录看似成功,但调用接口时会返回CORS错误。相关截图显示请求被CORS策略阻止,提示目标资源不存在Access-Control-Allow-Origin响应头。

当前配置代码如下:

Swagger生成配置

builder.Services.AddSwaggerGen(c =>
{
    c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme()
    {
        Name = "oauth2",
        Scheme = "oauth2",
        Type = SecuritySchemeType.OAuth2,
        Flows = new OpenApiOAuthFlows
        {
            Implicit = new OpenApiOAuthFlow
            {
                AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize"),
                TokenUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"),
                Scopes = new Dictionary<string, string>
                {
                    {  "openid", "openid" },
                    {  "profile", "profile" }
                }                
            }
        }
    });

    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "oauth2" },
                Scheme = "oauth2",
                Name = "oauth2",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.OAuth2,
            }, new [] { "openid", "profile" }
        }
    });
});

Swagger UI配置

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.OAuthClientId(clientId);
        c.OAuthClientSecret(clientSecret);
        c.OAuthScopeSeparator(" ");
        c.OAuthUseBasicAuthenticationWithAccessCodeGrant();
    });
}
解决建议

你遗漏了以下关键配置:

  • 配置并启用CORS策略
    在Program.cs中添加CORS服务配置,并在中间件管道中启用(注意顺序要在认证和Swagger之前):

    // 添加CORS服务
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("SwaggerPolicy", policy =>
        {
            policy.WithOrigins("https://localhost:<你的Swagger端口>") // 替换为实际的Swagger UI地址
                  .AllowAnyHeader()
                  .AllowAnyMethod()
                  .AllowCredentials(); // 必须启用,因为携带了认证Cookie/Token
        });
    });
    
    // 启用CORS,位置要在app.UseAuthentication()和app.UseSwagger()之前
    app.UseCors("SwaggerPolicy");
    
  • Azure AD应用注册的CORS与权限配置
    登录Azure门户,找到你的应用注册:

    1. 进入API权限→添加权限,为WebAPI添加专属作用域(比如api://<你的API客户端ID>/access_as_user),并在Swagger的Scopes中添加该作用域(仅openid和profile是身份作用域,不具备API访问权限)。
    2. 进入认证→平台配置,确认已添加Swagger UI的重定向URI(比如https://localhost:<你的Swagger端口>/swagger/oauth2-redirect.html)。
    3. 进入CORS,添加Swagger UI的源地址(比如https://localhost:<你的Swagger端口>),确保包含所有开发环境的测试地址。
  • 修正Swagger OAuth流程配置
    当前配置混用了隐式流(Implicit)和授权码流的配置项(OAuthUseBasicAuthenticationWithAccessCodeGrant),导致流程冲突。建议改为授权码流,并调整配置:

    // Swagger生成配置中的Flows改为AuthorizationCode
    Flows = new OpenApiOAuthFlows
    {
        AuthorizationCode = new OpenApiOAuthFlow
        {
            AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize"),
            TokenUrl = new Uri($"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token"),
            Scopes = new Dictionary<string, string>
            {
                { "api://<你的API客户端ID>/access_as_user", "访问WebAPI" },
                { "openid", "身份标识" },
                { "profile", "用户信息" }
            }
        }
    }
    
  • 检查中间件顺序
    确保中间件加载顺序正确,CORS必须在认证、Swagger之前:

    app.UseHttpsRedirection();
    app.UseCors("SwaggerPolicy");
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseSwagger();
    app.UseSwaggerUI();
    app.MapControllers();
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:12:41