无法加载http:// localhost:5000 / .known / openid-configuration:所请求的资源上不存在“ Access-Control-Allow-Origin”标头

Dot*_*ver 5 c# cors asp.net-core identityserver4

我是Identityserver4的新手,最近我看到了Identityserver团队提供的Quickstart8示例,其中包括3个项目1.Identityserver 2.Api 3.Client在我部署到iis时,它们在浏览器中都运行良好工作正常,它显示错误,如...

在此处输入图片说明

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

请帮我解决这个问题。

这是我的代码...

api(startup.cs)

using Microsoft.AspNetCore.Builder;
Run Code Online (Sandbox Code Playgroud)

使用Microsoft.Extensions.DependencyInjection;

名称空间Api {公共类Startup {公共无效ConfigureServices(IServiceCollection服务){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();
    }
}
Run Code Online (Sandbox Code Playgroud)

}

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 });
    }
}
Run Code Online (Sandbox Code Playgroud)

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

在此处输入图片说明

Mic*_*iey 0

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

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

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

相关配置

知道这一点后,一些配置设置就会发挥作用;让我们一起讨论它们吧。

IdentityServer 中的客户端设置

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

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

这可以在此处的Config课程中找到。

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

JS配置

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

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

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

API配置

此示例展示了 JS 客户端如何向 API 发出请求并将令牌发送到 IdentityServer 来验证它。

这里涉及到几个设置:

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

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

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