'Is there a way to get all existing clients in Identity Server?

I've below app structure

  • Authentication (.NET 5)
  • Web App (Angular)
  • Resource API

What I'm trying to achieve is to get my client js but I'm getting an error while hitting on

https://localhost:5005/_configuration/js

enter image description here

Here is my authentication application code:

public class Config
{
    public static IEnumerable<Client> Clients =>
        new Client[]
        {
            new Client
            {
                ClientId = "js",
                ClientName = "SPA OpenId Client",

                RequireClientSecret = false,
                AllowedGrantTypes = GrantTypes.Implicit,
                AllowAccessTokensViaBrowser = true,
                RequirePkce = false,
                RedirectUris = new List<string>()
                {
                    "http://localhost:4200/"
                },
                RequireConsent = false,
                PostLogoutRedirectUris = new List<string>()
                {
                    "http://localhost:4200/"
                },
                AllowedCorsOrigins = new List<string>()
                {
                    "http://localhost:4200"
                },
                AllowedScopes = new List<string>
                {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Address,
                    IdentityServerConstants.StandardScopes.Email,
                    "requisitionAPI",
                    "roles"
                }
            },
            new Client
            {
                ClientId = "requisitionswaggerui",
                ClientName = "Requisition Swagger UI",
                AllowedGrantTypes = GrantTypes.Implicit,
                ClientSecrets = new List<Secret>
                {
                    new Secret("secret".Sha256())
                },
                AllowAccessTokensViaBrowser = true,

                RedirectUris = { "https://localhost:44333/swagger/oauth2-redirect.html" },
                PostLogoutRedirectUris = {"https://localhost:44333/swagger/" },

                AllowedScopes =
                {
                    "requisitionAPI"
                }
            },
        };

    public static IEnumerable<ApiScope> ApiScopes =>
       new ApiScope[]
       {
           new ApiScope("requisitionAPI","Requisition API")
       };

    public static IEnumerable<ApiResource> ApiResources =>
      new ApiResource[]
      {
      };

    public static IEnumerable<IdentityResource> IdentityResources =>
      new IdentityResource[]
      {
          new IdentityResources.OpenId(),
          new IdentityResources.Profile(),
          new IdentityResources.Address(),
          new IdentityResources.Email(),
          new IdentityResource(
                "roles",
                "Your role(s)",
                new List<string>() { "role" })
      };
}

Oidc Configuration Controller

public class OidcConfigurationController : Controller
{
    private readonly ILogger<OidcConfigurationController> _logger;

    public OidcConfigurationController(IClientRequestParametersProvider clientRequestParametersProvider, ILogger<OidcConfigurationController> logger)
    {
        ClientRequestParametersProvider = clientRequestParametersProvider;
        _logger = logger;
    }

    public IClientRequestParametersProvider ClientRequestParametersProvider { get; }

    [HttpGet("_configuration/{clientId}")]
    public IActionResult GetClientRequestParameters([FromRoute] string clientId)
    {
        var parameters = ClientRequestParametersProvider.GetClientParameters(HttpContext, clientId);
        return Ok(parameters);
    }
}

Authentication.API Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));

        services.AddTransient<IProfileService, ProfileService>();

        services.AddIdentity<User, Role>()
            .AddRoles<Role>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();
        services.AddControllersWithViews();

        var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

        services.AddIdentityServer(options =>
        {
            options.IssuerUri = "https://localhost:44333";
            options.Authentication.CookieLifetime = TimeSpan.FromHours(2);
            options.Events.RaiseErrorEvents = true;
            options.Events.RaiseInformationEvents = true;
            options.Events.RaiseFailureEvents = true;
            options.Events.RaiseSuccessEvents = true;
        })
            .AddDeveloperSigningCredential()
            .AddInMemoryClients(Config.Clients)
            .AddInMemoryApiScopes(Config.ApiScopes)
            .AddInMemoryIdentityResources(Config.IdentityResources)
            .AddAspNetIdentity<User>();
        services.AddAuthentication();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseCors(builder => builder
         .AllowAnyOrigin()
         .AllowAnyMethod()
         .AllowAnyHeader());
        app.UseStaticFiles();
        app.UseRouting();
        app.UseIdentityServer();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
        });
    }

Client Side:

private async ensureUserManagerInitialized(): Promise<void> {
if (this.userManager !== undefined) {
  return;
}

let API_URL = `https://localhost:5005/${ApplicationPaths.ApiAuthorizationClientConfigurationUrl}`;
const response = await fetch(API_URL, this.setHeaders());
if (!response.ok) {
  throw new Error(`Could not load settings for '${ApplicationName}'`);
}

const settings: any = await response.json();
settings.automaticSilentRenew = true;
settings.includeIdTokenInSilentRenew = true;
this.userManager = new UserManager(settings);

this.userManager.events.addUserSignedOut(async () => {
  await this.userManager.removeUser();
  this.userSubject.next(null);
});
}

private getUserFromStorage(): Observable<IUser> {
return from(this.ensureUserManagerInitialized())
  .pipe(
    mergeMap(() => this.userManager.getUser()),
    map(u => u && u.profile));
}

private setHeaders(): any {
  const httpOptions = {
      headers: new HttpHeaders()
  };

  httpOptions.headers = httpOptions.headers.set('Content-Type', 'application/json');
  httpOptions.headers = httpOptions.headers.set('Accept', 'application/json');

  const token = this.GetToken();

  if (token !== '') {
      httpOptions.headers = httpOptions.headers.set('Authorization', `Bearer ${token}`);
  }

  return httpOptions;
}

I'm also sharing a detailed error below:

enter image description here

How to resolve this issue. Appreciate your time.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source