ASP.NET Core returns 使用身份服务器时出现 InternalServerError

ASP.NET Core returns InternalServerError while using Identity server

我正在尝试为我的网站添加身份服务器 API 作为其身份服务器 4 文档。当我试图从我的控制台应用程序调用 API 时,每次都是 returns InternalServerError.

这是我的身份服务器Config.cs

public static class Config
{
    // register api
    public static IEnumerable<ApiScope> ApiScopes => new List<ApiScope>
   {
        // in here add your api name 
      new ApiScope("api1", "My API")
   };

    // register client which is going to access api. eg: front-end application, mobile apps etc. can add multiple client.
    public static IEnumerable<Client> Clients => new List<Client>
    {
      new Client
      {
          // which is going to access
          ClientId = "client",
          // no interactive user, use the clientid/secret for authentication
         AllowedGrantTypes = GrantTypes.ClientCredentials,
         // secret for authentication
        ClientSecrets =
        {
            new Secret("secret".Sha256())
        },

        // scopes that client has access to
        AllowedScopes = { "api1" }

      }
    };

}

这里是身份服务器启动文件配置服务和配置函数

  public void ConfigureServices(IServiceCollection services)
        {
            // uncomment, if you want to add an MVC-based UI
            services.AddControllersWithViews();

            var builder = services.AddIdentityServer()
                .AddInMemoryApiScopes(Config.ApiScopes)
                .AddInMemoryClients(Config.Clients);

            builder.AddDeveloperSigningCredential();

          
            builder.AddDeveloperSigningCredential();
        }

        public void Configure(IApplicationBuilder app)
        {
            if (Environment.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // uncomment if you want to add MVC
            app.UseStaticFiles();
            app.UseRouting();

            app.UseIdentityServer();

            // uncomment, if you want to add MVC
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapDefaultControllerRoute();
            });
        }

这是我的 API 启动文件的配置服务和配置功能

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddAuthentication("Bearer")
                .AddJwtBearer("Bearer", options =>
                {
                    options.Authority = "https://localhost:14030/";
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = false
                    };
                }
                );
           
        }

        
   

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

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

这是我的 API 控制器

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

这是我的控制台应用程序客户端请求 api

 static async System.Threading.Tasks.Task Main(string[] args)
        {

            // discover endpoints from metadata
            var client = new HttpClient();

            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:14030");
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }

            // request token
            var tokenResponse = await client.RequestClientCredentialsTokenAsync(new ClientCredentialsTokenRequest
            {
                Address = disco.TokenEndpoint,
                ClientId = "client",
                ClientSecret = "secret",
                Scope = "api1"
            });

            if (tokenResponse.IsError)
            {
                Console.WriteLine(tokenResponse.Error);
                return;
            }

            Console.WriteLine(tokenResponse.Json);
            Console.WriteLine("\n\n");

            // call api
            var apiClient = new HttpClient();
            apiClient.SetBearerToken(tokenResponse.AccessToken);

            var response = await apiClient.GetAsync("https://localhost:5001/identity");
            if (!response.IsSuccessStatusCode)
            {
                Console.WriteLine(response.StatusCode);
            }
            else
            {
                var content = await response.Content.ReadAsStringAsync();
                Console.WriteLine(content);
            }
        }

我应该改正哪些错误。我非常感谢您宝贵的回答和努力。

感谢

我让代码正常工作,我将执行以下操作:

这里使用 HTTPS,而不是 HTTP:

var disco = await
   client.GetDiscoveryDocumentAsync("http://localhost:14030");

删除IdentityServer启动中的重复行class:

builder.AddDeveloperSigningCredential();

我会加入你的 API startup.cs

services.AddAuthorization();

在此处删除 URL 末尾的尾随 /:

options.Authority = "https://localhost:14030/";

要从您的 API 获得更多调试输出,您可以将以下两条跟踪行添加到您的 appsettings.Development.json 文件中:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information",
      "Microsoft.AspNetCore.Authentication": "Trace",
      "Microsoft.AspNetCore.Authorization": "Trace"
    }
  }
}

如果您想验证受众(并使用 IdentityServer4 v4.00),您可以添加:

services.AddControllers();

services.AddAuthentication("Bearer")
    .AddJwtBearer("Bearer", options =>
        {
            options.Authority = "https://localhost:14030";
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidAudiences = new[] {"https://localhost:14030/resources"},
                ValidateAudience = true
            };
        }
    );