身份服务器 4 - 配置了允许的来源但不允许来源

use*_*854 5 c# .net-core identityserver4

我在同一个项目中有一个 SPA 和 API,当我向 API 发出请求时,我不断收到以下错误。

AllowedOrigins configured and origin http://localhost:5000 is not allowed
CorsPolicyService did not allow origin: http://localhost:5000
Run Code Online (Sandbox Code Playgroud)

api的路径是:http://localhost:5000。我确保我在ClientCorsOrigins表中为客户端指定了来源,并且我还在我的Startup.cs

services.AddCors(options =>
            {
                options.AddPolicy("default", policy =>
                {
                    policy.WithOrigins("http://localhost:5000")
                        .AllowAnyHeader()
                        .AllowAnyMethod();
                });
            });
Run Code Online (Sandbox Code Playgroud)

我已经多次检查文档和配置,但当我在 ClientCorsOrigins 表中指定了原点时,我无法弄清楚为什么我会遇到这个问题。我正在使用谷歌浏览器。

Ant*_*pod 5

您需要使用您的 ClientId 和 Origin 在 [dbo].[ClientCorsOrigin] 表中添加一行/记录。

CorsPolicyProvider.cs 在第 62行进行了检查:

if (await corsPolicyService.IsOriginAllowedAsync(origin))
Run Code Online (Sandbox Code Playgroud)

当它返回false 时,您将在第 69行看到“ CorsPolicyService 不允许 origin: http://localhost:5000 ”消息。

我假设您正在使用 IdentityServer4.EntityFramework。这是来自位于 IdentityServer4.EntityFramework.Services 命名空间中的 CorsPolicyService.cs 的 IsOriginAllowedAsync 方法:

    /// <summary>
    /// Determines whether origin is allowed.
    /// </summary>
    /// <param name="origin">The origin.</param>
    /// <returns></returns>
    public Task<bool> IsOriginAllowedAsync(string origin)
    {
        // doing this here and not in the ctor because: https://github.com/aspnet/CORS/issues/105
        var dbContext = _context.HttpContext.RequestServices.GetRequiredService<IConfigurationDbContext>();

        var origins = dbContext.Clients.SelectMany(x => x.AllowedCorsOrigins.Select(y => y.Origin)).ToList();

        var distinctOrigins = origins.Where(x => x != null).Distinct();

        var isAllowed = distinctOrigins.Contains(origin, StringComparer.OrdinalIgnoreCase);

        _logger.LogDebug("Origin {origin} is allowed: {originAllowed}", origin, isAllowed);

        return Task.FromResult(isAllowed);
    }
Run Code Online (Sandbox Code Playgroud)

查看 isAllowed,它填充了来自 AllowedCrossOrigins 集合的数据,其内容存储在 [dbo].[ClientCorsOrigin] 表中。

因此,请仔细检查 ClientCorsOrigin 表中的内容。