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

IdentityServer4认证授权报错:TypeError: Failed to fetch及CORS问题求助

问题:IdentityServer4与Swagger UI集成时的CORS报错

环境信息

  • IdentityServer4部署地址:https://localhost:44311
  • 受保护API部署地址:https://localhost:44305
  • 异常现象:IdentityServer4的Admin API无CORS问题,但当前API在Swagger UI中触发跨域错误

错误详情

Swagger UI界面提示

Errors
Auth error TypeError: Failed to fetch

Chrome浏览器控制台报错

Access to fetch at 'https://localhost:44311/connect/token' from origin
'https://localhost:44305' has been blocked by CORS policy: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the
requested resource. If an opaque response serves your needs, set the request's mode to
'no-cors' to fetch the resource with CORS disabled.

相关代码

SampleController.cs

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Get.Caa.Security.IdentityServer.Configuration.Constants;

namespace Get.Caa.Security.IdentityServer.Api.Controllers
{

    /// <summary>
    /// Class
    /// </summary>
    [Authorize]
    [Route("api/test")]
    public class SampleController : ControllerBase
    {
        /// <summary>
        ///  Constructor
        /// </summary>
        public SampleController()
        {

        }

        /// <summary>
        /// Get Api
        /// </summary>
        /// <returns></returns>
        [HttpGet()]
        public IActionResult Get()
        {
            return Ok("IdentityServer4 authentication is working!!");
        }
    }
}

Program.cs

using Get.Caa.Security.IdentityServer.Extensions;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddIdentityServer(builder.Configuration, builder.Environment);

builder.Services.AddAuthorization();
builder.Services.AddControllers();

var app = builder.Build();

app.UseIdentityServer(builder.Configuration);

app.Run();

排查与解决方案

问题核心是IdentityServer4未配置允许API域名的跨域请求:Swagger UI从https://localhost:44305发起的/connect/token请求属于跨域操作,浏览器会先发送OPTIONS预请求,若IdentityServer4未返回正确的CORS响应头,浏览器会阻止后续请求。

1. 在IdentityServer4中配置CORS策略

找到IdentityServer4的启动配置文件(通常为Program.cs),添加CORS服务并指定允许的来源:

// 服务注册阶段添加CORS配置
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSwaggerOrigin", policy =>
    {
        policy.WithOrigins("https://localhost:44305")
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials(); // OAuth2请求需携带凭证,必须启用此项
    });
});

2. 在请求管道中启用CORS

注意CORS中间件必须放在UseIdentityServer之前,否则不会生效:

var app = builder.Build();

// 启用CORS策略
app.UseCors("AllowSwaggerOrigin");

app.UseIdentityServer(builder.Configuration);

app.Run();

3. 验证客户端配置(可选)

确保IdentityServer4中对应API的客户端配置已添加允许的CORS来源:

new Client
{
    ClientId = "your-api-client-id",
    // 其他客户端配置...
    AllowedCorsOrigins = { "https://localhost:44305" }
}

完成以上配置后,重启IdentityServer4和API,Swagger UI即可正常发起token请求,解决CORS报错问题。

内容的提问来源于stack exchange,提问作者Syed Rafey Husain

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 10:15:34