无法为 asp.net 核心中的身份服务器 4 启用 CORS

Not able to enable CORS for identity server 4 in asp.net core

好的,我已经为我的 dot net 核心 API 添加了 CORS 策略,但不知何故这些 CORS 策略不适用于身份服务器 4 端点。 我在以下 api 尝试注册用户:

    [EnableCors("AllowAllCorsPolicy")]
    [Route("api/User")]
    public class UserController : Controller
    {
        private readonly UserManager<ApplicationUser> _userManager;
        private IUserServices _userService;
        public UserController(UserManager<ApplicationUser> userManager, IUserServices userService)
        {
            _userManager = userManager;
            _userService = userService;
        }

        [HttpPost]
        public async Task<int> Post([FromBody]User userInfo)
        {
            var user = new ApplicationUser{  UserName = userInfo.Name, Email = userInfo.Email,
                UserTypeId = Constant.User, CustomerId = userInfo.CustomerId };

            //Follwing 3 lines give CORS issue.
            await _userManager.AddToRoleAsync(user, Constant.User);
            var userClaim = new Claim(Constant.User, user.Email.ToString(), ClaimValueTypes.Integer);
            await _userManager.AddClaimAsync(user, userClaim);

            // var userObj = _userService.AddNewUser(userInfo);
        }

现在,如果我使用上述身份服务器方法(AddToRoleAsync()AddClaimAsync()),我的客户端会出现 CORS 错误( angular 应用 运行 在不同的服务器上)

但是,如果我使用自定义方法注册用户,我不会收到 CORS 错误:

            //Don't get CORS error when commented below
            //await _userManager.AddToRoleAsync(user, Constant.User);
            //var userClaim = new Claim(Constant.User, user.Email.ToString(), ClaimValueTypes.Integer);
            //await _userManager.AddClaimAsync(user, userClaim);

            //use custom method
            var userObj = _userService.AddNewUser(userInfo);

要为 asp.net、startup.cs 启用 CORS,我正在做:

    public void ConfigureServices(IServiceCollection services)
            {
              services.AddCors(options =>
             {
                options.AddPolicy("AllowAllCorsPolicy",
                    builder => builder.AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials());
            });
            services.AddMvc();
          }


public void Configure(IApplicationBuilder app, IHostingEnvironment env,  IServiceProvider serviceProvider)
        {
            app.UseCors("AllowAllCorsPolicy");
        }

我什至尝试在 startup.cs 中手动添加 CORS headers,但没有成功:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,  IServiceProvider serviceProvider)
        {
            app.Use(async (context, next) =>
        {
            if (context.Request.Method == "OPTIONS")
                context.Response.StatusCode = (int)HttpStatusCode.OK;

            var headers = context.Response.Headers;
            if (headers.ContainsKey("Access-Control-Allow-Origin"))
            {
                headers["Access-Control-Allow-Origin"] = string.Join(",", context.Request.Headers["Referer"].Select(x => x.Substring(0, x.Length - 1)));
            }
            else
            {
                context.Response.Headers.Append("Access-Control-Allow-Origin", string.Join(",", context.Request.Headers["Referer"].Select(x => x.Substring(0, x.Length - 1))));
            }
            if (headers.ContainsKey("Access-Control-Allow-Headers"))
            {
                headers["Access-Control-Allow-Headers"] = "Origin, Content-Type, Accept, Client, Authorization, X-Auth-Token, X-Requested-With";
            }
            else
            {
                context.Response.Headers.Append("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Client, Authorization, X-Auth-Token, X-Requested-With");
            }
            if (headers.ContainsKey("Access-Control-Allow-Methods"))
            {
                headers["Access-Control-Allow-Credentials"] = "GET, POST, PATCH, PUT, DELETE, OPTIONS";
            }
            else
            {
                context.Response.Headers.Append("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS");
            }
            if (headers.ContainsKey("Access-Control-Allow-Credentials"))
            {
                headers["Access-Control-Allow-Credentials"] = "true";
            }
            else
            {
                context.Response.Headers.Append("Access-Control-Allow-Credentials", "true");
            }
            context.Response.Headers.Append("Access-Control-Expose-Headers", "X-Auth-Token");
            context.Response.Headers.Append("Vary", "Origin");
            await next();
        });
        }

我看过 this documentation for identityserver Options for CORS and also this CORS 文档,但帮助不大。

如果您将 IdentityServer 4 与客户端一起用于身份验证,则必须使用 IdentityServer 4 配置 CORS,请参阅:IdentityServer4CORS

IdentityServer4 CORS 仅用于令牌端点。 您所做的是为所有 controller/methods 配置 CORS,这在您的情况下可能是正确的。但是,如果您不在 identityserver4 上启用 CORS,您将无法检索令牌。

您可以将允许的 CORS 列表添加到将添加到身份服务器数据库的客户端,或者像这样添加一个全局默认值:

var cors = new DefaultCorsPolicyService(_loggerFactory.CreateLogger<DefaultCorsPolicyService>())
{
    AllowedOrigins = { "https://foo", "https://bar" }
};
services.AddSingleton<ICorsPolicyService>(cors);

请注意,您也可以手动将其添加到数据库中。

这适用于较新版本的服务器。

    services.AddSingleton<ICorsPolicyService>((container) => {
        var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
        return new DefaultCorsPolicyService(logger)
        {
            AllowAll = true
        };
    });

在此讨论中有更多详细信息,感谢原作者

https://github.com/IdentityServer/IdentityServer4/issues/4685