Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core ASP.NET Core在使用Identity server时返回InternalServerError_Asp.net Core_Asp.net Identity_Identityserver4 - Fatal编程技术网

Asp.net core ASP.NET Core在使用Identity server时返回InternalServerError

Asp.net core ASP.NET Core在使用Identity server时返回InternalServerError,asp.net-core,asp.net-identity,identityserver4,Asp.net Core,Asp.net Identity,Identityserver4,我正在尝试为我的web API添加identity server作为其identity server4文档。当我试图从控制台应用程序调用API时,每次都返回InternalServerError 这是我的Identity server Config.cs public static class Config { // register api public static IEnumerable<ApiScope> ApiScopes => new List<

我正在尝试为我的web API添加identity server作为其identity server4文档。当我试图从控制台应用程序调用API时,每次都返回InternalServerError

这是我的Identity server 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" }

      }
    };

}
这是我的API启动文件的congurationService和configure函数

  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();
            });
        }
 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启动类中的重复行:

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