title: Identity server issues AuthenticationScheme: Bearer was challenged for a token obtained by client credentials. How to find out the underlying error?
body: <p>I have trouble authenticating some integration tests requests when working with Identity Server 4 (ASP.NET Core 3.1).</p>
  
  <p>My setup is as follows:</p>
  
  <h3>Identity server configuration</h3>
  
  <pre><code>public static IEnumerable&lt;IdentityResource&gt; GetIdentityResources()
  {
      return new List&lt;IdentityResource&gt;
      {
          new IdentityResources.OpenId(),
          new IdentityResources.Email(),
          new IdentityResources.Profile(),
      };
  }
  
  public static IEnumerable&lt;ApiResource&gt; GetApiResources()
  {
      return new List&lt;ApiResource&gt;
      {
          new ApiResource("resourceapi", "Resource API")
          {
              Scopes = {new Scope("api.read")}
          }
      };
  }
  
  public static IEnumerable&lt;Client&gt; GetClients()
  {
      return new[]
      {
          new Client
          {
              RequireConsent = false,
              ClientId = "MY_CLIENT_ID",
              ClientName = "My Client Name",
              // code is required for SPA, client credentials for test runner
              AllowedGrantTypes = GrantTypes.CodeAndClientCredentials,
              AllowedScopes = {"openid", "profile", "email", "api.read"},
              RedirectUris = {"http://localhost:4201/auth-callback"},
              PostLogoutRedirectUris = {"http://localhost:4201/"},
              AllowedCorsOrigins = {"http://localhost:4201"},
              AllowAccessTokensViaBrowser = true,
              AccessTokenLifetime = 3600,
              RequireClientSecret = false
          }
      };
  }
  
  
  services.AddIdentity&lt;AppUser, IdentityRole&gt;()
      .AddEntityFrameworkStores&lt;AppIdentityDbContext&gt;()
      .AddDefaultTokenProviders();
  
  services.AddIdentityServer()
      .AddDeveloperSigningCredential()
      // this adds the operational data from DB (codes, tokens, consents)
      .AddOperationalStore(options =&gt;
      {
          options.ConfigureDbContext = builder =&gt; builder.UseSqlServer(Configuration.GetConnectionString("Default"));
          // this enables automatic token cleanup. this is optional.
          options.EnableTokenCleanup = true;
          options.TokenCleanupInterval = 30; // interval in seconds
      })
      //.AddInMemoryPersistedGrants()
      .AddInMemoryIdentityResources(Config.GetIdentityResources())
      .AddInMemoryApiResources(Config.GetApiResources())
      .AddInMemoryClients(Config.GetClients())
      .AddAspNetIdentity&lt;AppUser&gt;();
  </code></pre>
  
  <h3>ASP.NET Core client</h3>
  
  <pre><code>// this is called from Startup.ConfigureServices
  public static void ConfigureSecurity(this IServiceCollection services, IConfiguration configuration)
  {
      services.AddAuthentication(options =&gt;
      {
          options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
          options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
      }).AddJwtBearer(o =&gt;
      {
          o.Authority = configuration.GetSection("Idam").GetValue&lt;string&gt;("BaseUrl");  // http://localhost:54916
          o.Audience = configuration.GetSection("Idam").GetValue&lt;string&gt;("Audience");  // "resourceapi"
          o.RequireHttpsMetadata = false;
      });
  
      services.AddAuthorization();
  }
  </code></pre>
  
  <h3>Integration tests code</h3>
  
  <pre><code>var client = new HttpClient();
  var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
  {
      Address = $"{IdentityServerUrl}/connect/token",
      ClientId = "MY_CLIENT_ID",
      ClientSecret = IdentityServerPass,
      Scope = "api.read"
  
  }).ConfigureAwait(false);
  tokenResponse.HttpResponse.EnsureSuccessStatusCode();
  </code></pre>
  
  <p>Here I receive a bearer token, but does not seem to be accepted (Identity Server issues the error below). It looks like the following:</p>
  
  <pre><code>{
    "nbf": 1587392198,
    "exp": 1587395798,
    "iss": "http://localhost:54916",
    "aud": "resourceapi",
    "client_id": "STACKOVERFLOW_METRO_MIRROR",
    "scope": [
      "api.read"
    ]
  }
  
  
  &gt; IdentityServer4.Hosting.IdentityServerMiddleware: Information:
  &gt; Invoking IdentityServer endpoint:
  &gt; IdentityServer4.Endpoints.TokenEndpoint for /connect/token
  &gt; IdentityServer4.Validation.TokenRequestValidator: Information: Token
  &gt; request validation success, {   "ClientId":
  &gt; "STACKOVERFLOW_METRO_MIRROR",   "ClientName": "My Client Name",
  &gt; "GrantType": "client_credentials",   "Scopes": "api.read",   "Raw": {
  &gt;     "grant_type": "client_credentials",
  &gt;     "scope": "api.read",
  &gt;     "client_id": "MY_CLIENT_ID",
  &gt;     "client_secret": "***REDACTED***"   } } Microsoft.AspNetCore.Hosting.Diagnostics: Information: Request
  &gt; starting HTTP/1.1 GET
  &gt; http://localhost:44324/api/GeneralData/GetAllTags  
  &gt; Microsoft.AspNetCore.ResponseCaching.ResponseCachingMiddleware:
  &gt; Information: No cached response available for this request.
  &gt; Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:
  &gt; Information: Authorization failed.
  &gt; Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler:
  &gt; Information: AuthenticationScheme: Bearer was challenged.
  </code></pre>
  
  <p>Since my setup also includes a SPA that is able to successfully authenticate (login via Identity Server login form -> get token -> API uses token with success), I decrypted such a token to see if I see any relevant difference that might reveal what I am missing for the testing authentication flow:</p>
  
  <pre><code>{
    "nbf": 1587393059,
    "exp": 1587396659,
    "iss": "http://localhost:54916",
    "aud": "resourceapi",
    "client_id": "MY_CLIENT_ID",
    "sub": "fd351b3b-dfb2-4f2f-8987-af9d23c9dc6e",
    "auth_time": 1587393055,
    "idp": "local",
    "given_name": "test",
    "email": "test@example.com",
    "scope": [
      "openid",
      "email",
      "profile",
      "api.read"
    ],
    "amr": [
      "pwd"
    ]
  }
  </code></pre>
  
  <h3>ASP.NET Core Web API Startup.cs</h3>
  
  <pre><code>public void ConfigureServices(IServiceCollection services)
  {
      services.ConfigureCustomServices();
  
      services.ConfigureSettings(Configuration);
      services.ConfigureSecurity(Configuration);
      services.ConfigureMvc();
      services.BindLogging();
  
      services.ConfigureRedisCache(Configuration);
      services.ConfigureApiExplorer();
      services.AddHttpContextAccessor();
  
      services.AddDbContext(Configuration);
      ConfigureAuditNet();
  
      services.AddCorsAndPolicy();
  
      services.ConfigureHangfire(Configuration);
  
      services.AddSignalR();
      services.AddAutoMapper(typeof(QuestionProfile).Assembly);
      services.AddHealthChecks();
  
      services
          .AddControllers();
  }
  
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env,
      ILoggingService logger, IHostApplicationLifetime lifetime, IServiceProvider serviceProvider,
      ISoApiDailyRequestInfoService soApiDailyRequestInfoService)
  {
      app.UseResponseCaching();
  
      app.UseMiddleware&lt;ResponseTimeMiddleware&gt;();
  
      app.ProtectHangfireDashboard();
  
      app.ConfigureExceptionPage(env);
  
      app.StartHangFireJobs(serviceProvider, Configuration);
  
      ConfigureApplicationLifetime(logger, lifetime, soApiDailyRequestInfoService);
  
      app.UseHttpsRedirection();
  
      app.UseRouting();
      app.UseCors("CorsPolicy");
  
      app.UseAuthentication();
      app.UseAuthorization();
      app.EnsureAppUserMiddleware();
  
      app.UseEndpoints(endpoints =&gt;
      {
          endpoints.MapControllers();
  
          endpoints.MapHub&lt;PostHub&gt;("/post");
          endpoints.MapHealthChecks("/health");
      });
  
      app.ConfigureAuditMiddleware();
      app.UseSwagger();
  }
  </code></pre>
  
  <p>Unfortunately, the Identity server provides a very generic error and I do see what I missing here.</p>
  
  <p><strong>Question:</strong> Identity server issues <code>AuthenticationScheme: Bearer was challenged</code> for a token obtained by client credentials. How to find out the underlying error?</p>