Мы используем IS4 (версия 2.3.2) для защиты веб-приложения и API. Когда я отправляю код в нашу промежуточную среду, я получаю сообщение об ошибке, которая, по-видимому, связана с сертификатом подписи.
Вот IS4 Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Id.Server.Data;
using Id.Server.Models;
using Id.Server.Services;
using System.Reflection;
using IdentityServer4.Services;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using System.Security.Cryptography.X509Certificates;
using System.IO;
namespace Id.Server
{
public class Startup
{
private readonly ILogger<Startup> _logger;
public Startup(IConfiguration configuration, IHostingEnvironment hostingEnvironment, ILogger<Startup> logger)
{
Configuration = configuration;
HostingEnvironment = hostingEnvironment;
_logger = logger;
}
public IConfiguration Configuration { get; }
public IHostingEnvironment HostingEnvironment { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var appUsersConnectionString = Configuration.GetConnectionString("AppUserConnectionString");
var idSrvConfigConnectionString = Configuration.GetConnectionString("IdentityConfigConnectionString");
var loggingConnectionString = Configuration.GetConnectionString("LoggingDbConnection");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
_logger.LogTrace($"Environment:Trace:{HostingEnvironment.EnvironmentName}");
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(appUsersConnectionString,
o => o.MigrationsHistoryTable("__EFMigrationsHistory_Users","nasa")));
services.AddDbContext<IdentityLogContext>(options =>
options.UseSqlServer(loggingConnectionString,
b => b.MigrationsHistoryTable("__EFMigrationsHistory_IdServer", "nasa")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
_logger.LogTrace("Start identityServer Builder");
var identityServerBuilder = services.AddIdentityServer(options =>
{
options.Events.RaiseErrorEvents = true;
options.Events.RaiseInformationEvents = true;
options.Events.RaiseFailureEvents = true;
options.Events.RaiseSuccessEvents = true;
})
.AddAspNetIdentity<ApplicationUser>()
// this adds the config data from DB (clients, resources)
.AddConfigurationStore(options =>
{
options.DefaultSchema = "comp";
options.ConfigureDbContext = b =>
b.UseSqlServer(idSrvConfigConnectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.DefaultSchema = "comp";
options.ConfigureDbContext = b =>
b.UseSqlServer(idSrvConfigConnectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
// options.TokenCleanupInterval = 15; // frequency in seconds to cleanup stale grants. 15 is useful during debugging
});
_logger.LogTrace("Adding ProfileService");
services.AddTransient<IProfileService, ProfileService>();
if (HostingEnvironment.IsDevelopment())// || HostingEnvironment.IsStaging())
{
_logger.LogTrace("Developer Signing in effect");
identityServerBuilder.AddDeveloperSigningCredential();
}
else
{
_logger.LogTrace("Signing Credentials");
var certPath = Path.Combine(HostingEnvironment.ContentRootPath, $"{HostingEnvironment.EnvironmentName}.{Configuration["Certificates:TokenSigning"]}");
_logger.LogTrace($"Cert Path: {certPath}");
var tokenSigningCertificate = new X509Certificate2(certPath, "");
_logger.LogTrace("Adding token signing cert to identity server builder.");
identityServerBuilder.AddSigningCredential(tokenSigningCertificate);
_logger.LogTrace("Signing Cert Added");
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment() || env.IsStaging())
{
//app.UseBrowserLink();
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentityServer();
app.UseMvcWithDefaultRoute();
}
}
}
Когда я заставляю среду Staging использовать DeveloperSigningCertificate, тогда появляется страница входа в систему, и все работает, но если это разрешено, используйте Staging.SigningCert.pfx (самозаверяющий сертификат) мы получаем следующую ошибку в журналах:
System.NullReferenceException: ссылка на объект не установлена для экземпляра объекта. в IdentityServer4.ResponseHandling.DiscoveryResponseGenerator.CreateJwkDocumentAsync () в IdentityServer4.Endpoints.DiscoveryKeyEndpoint.ProcessAsync (HttpContext контекст) в IdentityServer4.Hosting.IdentityServerMiddleware.Invoke (HttpContext контекст, IEndpointRouter маршрутизатор, IUserSession сессия, IEventService события) на IdentityServer4.Hosting.IdentityServerMiddleware. Вызвать (контекст HttpContext, маршрутизатор IEndpointRouter, сеанс IUserSession, события IEventService) в Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke (контекст HttpContext) в Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddlewareverserver.Intext.Invoke (контекст HttpContext) в Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke (контекст HttpContext) в Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke (контекст HttpContextEm.Ext.Exchange.Exchange.Exchange.Exchange.Exception. e.Invoke (HttpContext httpContext) в Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke (HttpContext httpContext) в Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Inteke * 1011веб-приложение и API указывают, что ни один из них не сталкивается с ошибками. Все журналы трассировки проверяются и выполняются на стороне AddSigningCertificate. В браузере появляется страница с ошибками, отображаются 3 разные ошибки.
1)
System.Net.Http.HttpRequestException: Код состояния ответа не указывает на успех: 500 (Внутренняя ошибка сервера). в System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode () в Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync (строковый адрес, CancellationToken cancel)
2)
1024 *1022* 1022 * 1022.IO.IOException: IDX20804: невозможно получить документ из: '
http://identity.nasanew.local/.well-known/openid-configuration/jwks'. ---> System.Net.Http.HttpRequestException: код состояния ответа не указывает на успешность: 500 (внутренняя ошибка сервера). в System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode () в Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync (String address, CancellationToken cancel) --- Конец внутренней трассировки стека исключений --- в Microsoft.IdentityMocuGetDocumentAsync (Строковый адрес, CancellationToken cancel) в Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync (Строковый адрес, извлечение IDocumentRetriever, CancellationToken cancel) в Microsoft.IdentityModel.Proetcols.GoConnect.Configuration1028 *
3)
System.InvalidOperationException: IDX20803: невозможно получить конфигурацию из: 'http://identity.nasanew.local/.well-known/openid-configuration'. ---> System.IO.IOException: IDX20804: невозможно получитьдокумент из: 'http://identity.nasanew.local/.well-known/openid-configuration/jwks'. ---> System.Net.Http.HttpRequestException: код состояния ответа не указывает на успех: 500 (Внутренняя ошибка сервера). в System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode ()в Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync (Строковый адрес, CancellationToken cancel) --- Конец внутренней трассировки стека исключений --- в Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync (Строковый адрес, CancellationLot.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync (Строковый адрес, извлечение IDocumentRetriever, CancellationToken cancel) в Microsoft.IdentityModel.Protocols.ConfigurationManager 1.GetConfigurationAsync(CancellationToken cancel)
--- End of inner exception stack trace ---
at Microsoft.IdentityModel.Protocols.ConfigurationManager
1.GetConfigurationAsync. Свойства) в Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.ChallengeAsync (свойства AuthenticationProperties) в Microsoft.AspNetCore.Authentication.AuthenticationService.ChallengeAsync (контекст HttpContext, схема String, свойства AuthenticationProperties) в Microsoft.Ahallenge.sp. ExecuteResultAsync (контекст ActionContext) в Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeResultAsync (результат IActionResult) в Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAlwaysRunResultFilters () InInF.Inc. Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync () в Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke (HttpContext httpContext) в Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Inthespace. Вызов (контекст HttpContext) в Infragistics.Web.Mvc.UploadStatusHandler.Invoke (контекст HttpContext) в Infragistics.Web.Mvc.MiddleWare.UploadModuleMiddleware.Invoke (контекст HttpContext) в контексте H. 1038 *
Я просто не уверен, где и что посмотреть, чтобы решить эти проблемы, когда не используется вход для разработчиков. ж, любая помощь будет отличной.