Произошло несанкционированное исключение при отправке запроса https asp. net core 2.2 и идентификационного сервера 4. - PullRequest
0 голосов
/ 17 марта 2020

У меня есть 3 службы, которые связываются между ними через запросы https и один хост сервера идентификации. Идентификационный сервер настроен так:

public void ConfigureServices(IServiceCollection services)
    {
       var connectionString = Configuration.GetConnectionString(ConnectionString);
       services.AddTransient<IUserManagement, UserManagement>();
       services.AddTransient<IUserValidator, UserValidator>();
       services.AddSingleton<Func<IDbConnection>>(() => new SqlConnection(Configuration.GetConnectionString("StudioFlyUser")));

        var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
        _logger.LogInformation("Configuring services");
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        Console.WriteLine($"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\\CertificateScript\\StudioFlyClient.pfx");
        services.AddIdentityServer()
            .AddSigningCredential(new X509Certificate2($"{Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)}\\CertificateScript\\StudioFlyClient.pfx", "studioFly"))
            .AddDeveloperSigningCredential()
            .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = b => b.UseSqlServer("Server=localhost\\SQLEXPRESS; Database=StudioFlyOAuth;Trusted_Connection=True;",
                    sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = b => b.UseSqlServer("Server=localhost\\SQLEXPRESS; Database=StudioFlyOAuth;Trusted_Connection=True;",
                    sql => sql.MigrationsAssembly(migrationsAssembly));
            });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        MigrateInMemoryDataToSqlServer(app);
        app.UseDeveloperExceptionPage();
        app.UseIdentityServer();
        app.UseStaticFiles();
        app.UseMvcWithDefaultRoute();
        app.UseHttpsRedirection();
    }

Один из сервисов настроен для взаимодействия с идентификационным сервером:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
        services.AddSingleton<IUserManagement, UserManagement>();
        services.AddApiVersioning(o =>
        {
            o.ReportApiVersions = true;
            o.AssumeDefaultVersionWhenUnspecified = true;
            o.DefaultApiVersion = new ApiVersion(1, 0);
        });
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
        })
             .AddIdentityServerAuthentication(o =>
             {
                 o.Authority = "https://localhost:22001";
                 o.ApiName = "studioFly";
                 o.RequireHttpsMetadata = false;
             })

            .AddCookie()
            .AddOpenIdConnect(o =>
            {
                o.Authority = "https://localhost:22001/";
                o.RequireHttpsMetadata = false;
                o.ClientId = "studioFly_userManagement";
                o.ClientSecret = "secret";
                o.ResponseType = "id_token code";
                o.GetClaimsFromUserInfoEndpoint = true;
                o.SaveTokens = true;
                o.Scope.Add("studioFly");
                o.Scope.Add("offline_access");
                o.Scope.Add("email");
                o.CorrelationCookie.Path = "/";
                o.NonceCookie.Path = "/";
            });
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    }

Второй сервис определен так:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
        services.AddSingleton<IAppointmentsManagement, AppointmentsManagement>();
        services.AddApiVersioning(o =>
        {
            o.ReportApiVersions = true;
            o.AssumeDefaultVersionWhenUnspecified = true;
            o.DefaultApiVersion = new ApiVersion(1, 0);
        });
        services.AddAuthentication(options =>
            {
                options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
              .AddIdentityServerAuthentication(o =>
              {
                  o.RequireHttpsMetadata = false;
                  o.Authority = "https://localhost:22001/";
                  o.ApiName = "studioFly";
              })

             .AddCookie()
             .AddOpenIdConnect(o =>
             {
                 o.Authority = "https://localhost:22001/";
                 o.RequireHttpsMetadata = false;
                 o.ClientId = "studioFly_appointmentManagement";
                 o.ClientSecret = "secret";
                 o.ResponseType = "id_token code";
                 o.GetClaimsFromUserInfoEndpoint = true;
                 o.SaveTokens = true;
                 o.Scope.Add("studioFly");
                 o.Scope.Add("offline_access");
                 o.Scope.Add("email");
             });
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
    }

Клиенты определены следующим образом:

new Client
            {
                ClientId = "studioFly_appointmentManagement",
                ClientSecrets = new [] { new Secret("secret".Sha256()) },
                ClientUri="https://localhost:25001",
                AllowedGrantTypes = GrantTypes.Hybrid,
                AllowedScopes = new [] {
                    IdentityServerConstants.StandardScopes.OpenId,
                    IdentityServerConstants.StandardScopes.Profile,
                    IdentityServerConstants.StandardScopes.Email,
                    "studioFly"
                },
                AllowOfflineAccess = true,
                AllowAccessTokensViaBrowser = true,
                RequireConsent = false,
                RedirectUris = new [] { "https://localhost:25001/signin-oidc" },
                PostLogoutRedirectUris = { "https://localhost:25001/signout-callback-oidc" },
            }
 new Client
             {
                 ClientId = "studioFly_userManagement",
                 ClientSecrets = new [] { new Secret("secret".Sha256()) },
                 ClientUri="https://localhost:24001",
                 AccessTokenType = AccessTokenType.Jwt,
                 AllowedGrantTypes = GrantTypes.Implicit,
                 AllowedScopes = new [] {
                     //IdentityServerConstants.StandardScopes.OpenId,
                     IdentityServerConstants.StandardScopes.Profile,
                     IdentityServerConstants.StandardScopes.Email,
                     "studioFly"
                 },
                 AllowOfflineAccess = true,
                 AllowAccessTokensViaBrowser = true,
                 RequireConsent = false,
             },

Когда я отправляю запрос https на сервер управления пользователями, я получаю неавторизованного клиента. Я не понимаю почему.

...