DotNetLover
DotNetLover

Reputation: 229

Failed to load http://localhost:5000/.well-known/openid-configuration: No 'Access-Control-Allow-Origin' header is present on the requested resource

I am a newbie to identityserver4, recently I have seen the Quickstart8 sample provided by the identityserver team, in that 3 project are included 1.Identityserver 2. Api 3.Client all are working fine in the browser when I deployed to iis they are not working properly it is showing error like...

enter image description here

I am using javascript client ...

Please help me with this issue.

This is my code...

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 (Identity Controller)

[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();
    }
}

I'm not able to access http://localhost:5000/.well-known/openid-configuration

enter image description here

Upvotes: 8

Views: 27761

Answers (5)

How 'bout a Fresca
How 'bout a Fresca

Reputation: 2317

I was running into this issue also with an Angular 9 app and a .net core web api project deployed to Azure in separate app services/endpoints. I am using Azure DevOps for CI/CD and ultimately what I realized is that in the deployed web.config for the API I had:

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

This was causing an issue because the WebHostBuilder was then using my Development configuration to initialize the Configuration for the Startup class, and that is why localhost was being used at all, since that is what is specified in my appsettings.Development.json file (my understanding - if I have it wrong I'm sure somebody will chime in :)).

I added a web.Staging.config file to my project with

    <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"/>

and my CI build is now transforming the web.config and my deployed ecosystem is healthy.

Upvotes: 0

eveex
eveex

Reputation: 1

I fixed problem by open IdentityServer port in firewall.

Struggling to much time for fixing this

Upvotes: 0

DotNetLover
DotNetLover

Reputation: 229

Finally i solved the problem by giving the sql login permission for Login failed for user 'IIS APPPOOL\IdServe

Upvotes: 0

mackie
mackie

Reputation: 5264

You don't need to do anything special here, ISD4 handles CORS properly out of the box. You need to specify http://localhost:5003 in the CORS origins for your client config. IDS4 will pick this up and allow the request to the discovery endpoint.

Upvotes: 0

Micka&#235;l Derriey
Micka&#235;l Derriey

Reputation: 13714

I think the sample doesn't work anymore when you run the projects from IIS because the addresses, or more precisely the ports, are not the same.

Ports used when run in IIS Express

When you run the projects through Visual Studio or use dotnet run, the URL over which the project is hosted is driven by a file called launchSettings.json in the Properties folder of your project.

Associated configuration

Knowing this there's a few configuration settings that come into play; let's go together over them.

Client settings in IdentityServer

When you define a client (i.e. an application that will federate its authentication to IdentityServer), you get to specify a few things, like:

  • to which URL(s) is IdentityServer allowed to redirect the user after logging in or logging out;
  • if this is a JS client, from which URL(s) should the browser be allowed to initiate an authorisation request

This can be found in the Config class over here.

You'll notice that all the URLs specified in that config point to where the JavaScriptClient is hosted when using IIS Express; you'll need to update those to the URL of the JS client when deployed to IIS.

JS configuration

Since in this example, the JS client makes a request directly to IdentityServer, some settings are defined in the JS application itself; we can find them in the app.js file:

  • authority is the IdentityServer URL - localhost:5000 is correct when we use IIS Express
  • redirect_uri and post_logout_redirect_uri use localhost:5003 which is the JS client URL when we use IIS Express

Again, you'll need to update all those values to match the URLs where both the applications are hosted when you use IIS.

API configuration

This sample shows how the JS client can make a request to the API and have it send the token to IdentityServer to validate it.

There are a few settings involved here:

  • The JS client needs to know the URL of the API - this is defined again in app.js in the JS client
  • The API needs to know how to reach IdentityServer - we'll find this in Startup.cs of the API
  • The API needs to allow, through a CORS policy, the browser to make an AJAX request to its endpoints, and that again is done in the Startup class in the API project

Once more, you'll need to update all those URLs to match the ones used when you deploy your projects to IIS.

Hopefully I didn't miss anything ;-)

Upvotes: 0

Related Questions