【问题标题】:Failed to load http://localhost:5000/.well-known/openid-configuration: No 'Access-Control-Allow-Origin' header is present on the requested resource无法加载 http://localhost:5000/.well-known/openid-configuration:请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2019-01-03 00:52:31
【问题描述】:

我是identityserver4的新手,最近看到了identityserver团队提供的Quickstart8示例,其中包括3个项目1.Identityserver 2. 当我部署到 iis 时,Api 3.Client 在浏览器中都可以正常工作,它们不能正常工作,它会显示错误,例如...

我正在使用 javascript 客户端...

请帮我解决这个问题。

这是我的代码...

API (startup.cs)

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Api
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                .AddAuthorization()
                .AddJsonFormatters();
        services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority = "http://localhost:5000";
                options.RequireHttpsMetadata = false;

                options.ApiName = "api1";
            });

        services.AddCors(options =>
        {
            // this defines a CORS policy called "default"
            options.AddPolicy("default", policy =>
            {
                policy.WithOrigins("http://localhost:5003")
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseCors("default");

        app.UseAuthentication();

        app.UseMvc();
    }
}

}

Api(身份控制器)

[Route("[controller]")]
[Authorize]
public class IdentityController : ControllerBase
{
    [HttpGet]
    public IActionResult Get()
    {
        return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
    }
}

QuickstartIdentityServer (startup.cs)

 public class Startup
{


    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        string connectionString = @"Data Source=DOTNET-Foo;Initial Catalog=IdentityServer4;Integrated Security=True";
        var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        // configure identity server with in-memory stores, keys, clients and scopes
        services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddTestUsers(Config.GetUsers())
            // this adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                    builder.UseSqlServer(connectionString,
                        sql => sql.MigrationsAssembly(migrationsAssembly));
            });
            // this adds the operational data from DB (codes, tokens, consents)
            //.AddOperationalStore(options =>
            //{
            //    options.ConfigureDbContext = builder =>
            //        builder.UseSqlServer(connectionString,
            //            sql => sql.MigrationsAssembly(migrationsAssembly));

        //    // this enables automatic token cleanup. this is optional.
        //    options.EnableTokenCleanup = true;
        //    options.TokenCleanupInterval = 30;
        //});

        services.AddAuthentication()
            .AddGoogle("Google", options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;

                options.ClientId = "434483408261-55tc8n0cs4ff1fe21ea8df2o443v2iuc.apps.googleusercontent.com";
                options.ClientSecret = "3gcoTrEDPPJ0ukn_aYYT6PWo";
            })
            .AddOpenIdConnect("oidc", "OpenID Connect", options =>
            {
                options.SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme;
                options.SignOutScheme = IdentityServerConstants.SignoutScheme;

                options.Authority = "https://demo.identityserver.io/";
                options.ClientId = "implicit";

                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role"
                };
            });

    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
           // IdentityServerDatabaseInitialization.InitializeDatabase(app);
        }
        app.UseIdentityServer();
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
    }
}

我无法访问 http://localhost:5000/.well-known/openid-configuration

【问题讨论】:

  • 你正在启用 cors,只是不要:|
  • “只是不要”不是好的建议。许多架构都需要 CORS。 “确保你知道你在做什么”更好。

标签: c# asp.net-core identityserver4


【解决方案1】:

我认为当您从 IIS 运行项目时,该示例不再起作用,因为地址,或者更准确地说是端口不同。

在 IIS Express 中运行时使用的端口

当您通过 Visual Studio 运行项目或使用 dotnet run 时,托管项目的 URL 由项目的 Properties 文件夹中名为 launchSettings.json 的文件驱动。

关联配置

了解这一点后,一些配置设置就会发挥作用;让我们一起解决它们。

IdentityServer 中的客户端设置

当您定义客户端(即,将其身份验证联合到 IdentityServer 的应用程序)时,您需要指定一些内容,例如:

  • IdentityServer 允许在登录或注销后将用户重定向到哪个 URL;
  • 如果这是一个 JS 客户端,应该允许浏览器从哪个 URL 发起授权请求

这可以在Configover here 中找到。

您会注意到,在使用 IIS Express 时,该配置中指定的所有 URL 都指向 JavaScriptClient 的托管位置;部署到 IIS 时,您需要将这些更新为 JS 客户端的 URL。

JS 配置

由于本例中JS客户端直接向IdentityServer发起请求,一些设置是在JS应用本身中定义的;我们可以在app.js 文件中找到它们:

  • authority 是 IdentityServer URL - 当我们使用 IIS Express 时,localhost:5000 是正确的
  • redirect_uripost_logout_redirect_uri 使用 localhost:5003,这是我们使用 IIS Express 时的 JS 客户端 URL

同样,当您使用 IIS 时,您需要更新所有这些值以匹配托管这两个应用程序的 URL。

API 配置

此示例展示了 JS 客户端如何向 API 发出请求并将令牌发送到 IdentityServer 以对其进行验证。

这里涉及到一些设置:

  • JS 客户端需要知道 API 的 URL - 这在 JS 客户端的 app.js 中再次定义
  • API 需要知道如何访问 IdentityServer - 我们将在 API 的 Startup.cs 中找到它
  • API 需要通过 CORS 策略允许浏览器向其端点发出 AJAX 请求,这同样在 API 项目的 Startup class 中完成

再一次,您需要更新所有这些 URL 以匹配您将项目部署到 IIS 时使用的那些。

希望我没有错过任何东西 ;-)

【讨论】:

  • 感谢 Mickael 的回答.. 即使我无法获得它,我也完成了您提到的步骤,但是如果我使用 Visual Studio 运行“Identiserver”并在 (iis-port 5001)和 iis 端口 5003 中的 javascript 它工作正常......但只有当我在端口 iis 5000 中运行 identityserver 时,javascript 客户端抛出错误(iis 端口 5003)
  • 哈,那么您在 IIS Express 和 IIS 中一直使用相同的端口吗?如果是这样的话,我的回答就离题了。当IdentityServer在IIS上运行时,您能否检查一下您是否可以访问localhost:5000/.well-known/openid-configuration
  • 实际上我无法访问该网址,但我可以访问“localhost:5000”但不能访问 localhost:5000/.well-known/openid-configuration
  • 好的。在这个阶段,我建议通过删除 IdSrv 管道设置中的 if clause 来在所有环境中启用开发人员异常页面,然后看看它会带来什么。要清楚,您需要保留app.UseDeveloperExceptionPage(); 位,只需将其从if 中取出即可。
  • 非常感谢 mickael,我启用了开发人员异常,它显示 SqlException: Cannot open database "IdentityServer4" 登录请求。登录失败。用户 'IIS APPPOOL\IdServer' 登录失败在授予登录权限后它工作......
【解决方案2】:

您不需要在这里做任何特别的事情,ISD4 开箱即用地正确处理 CORS。您需要在客户端配置的 CORS 来源中指定 http://localhost:5003。 IDS4 将选择它并允许对发现端点的请求。

【讨论】:

    【解决方案3】:

    最后我通过为用户 'IIS APPPOOL\IdServe 授予登录失败的 sql 登录权限来解决问题

    【讨论】:

      【解决方案4】:

      我通过在防火墙中打开 IdentityServer 端口解决了问题。

      花费大量时间来解决这个问题

      【讨论】:

        【解决方案5】:

        我也遇到了这个问题,一个 Angular 9 应用程序和一个 .net 核心 web api 项目在单独的应用程序服务/端点中部署到 Azure。我正在为 CI/CD 使用 Azure DevOps,最终我意识到在为 API 部署的 web.config 中:

            <environmentVariable name="ASPNETCORE_HTTPS_PORT" value="44340"/>
            <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Development"/>
        

        这导致了一个问题,因为 WebHostBuilder 然后使用我的开发配置来初始化 Startup 类的配置,这就是为什么要使用 localhost,因为这是我的 appsettings.Development.json 中指定的文件(我的理解 - 如果我错了,我相信有人会插话:))。

        我在我的项目中添加了一个 web.Staging.config 文件

            <environmentVariable name="ASPNETCORE_HTTPS_PORT" value="443" xdt:Locator="Match(name)" xdt:Transform="Replace"/>
            <environmentVariable name="ASPNETCORE_ENVIRONMENT" value="Staging" xdt:Locator="Match(name)" xdt:Transform="Replace"/>
        

        我的 CI 构建现在正在改变 web.config,我部署的生态系统很健康。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-10-10
          • 2021-06-02
          • 1970-01-01
          • 2015-10-01
          • 1970-01-01
          • 2016-01-12
          • 1970-01-01
          • 2015-03-29
          相关资源
          最近更新 更多