IdentityServer4 を使用して認証サーバーをセットアップしようとしています。コードを実行してテスト データを生成しようとすると、次のエラーが発生します。以下はコードです
private static void InitializeDbTestData(IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<UserDbContext>().Database.Migrate();
var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
if (!context.Clients.Any())
{
foreach (var client in Clients.Get())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
if (!context.Scopes.Any())
{
foreach (var clientSope in Scopes.Get())
{
context.Scopes.Add(clientSope.ToEntity());
}
context.SaveChanges();
}
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (!userManager.Users.Any())
{
foreach (var applicationUser in Users.Get())
{
foreach (var claim in applicationUser.UserClaims)
{
//ExtendedClaimsProvider.CreateClaim()
applicationUser.Claims.Add(new IdentityUserClaim<Guid>
{
UserId = applicationUser.Id,
ClaimType = claim.Type,
ClaimValue = claim.Value,
});
}
userManager.CreateAsync(applicationUser, "Password123!").Wait();
}
}
}
}
エラーは次の場合に生成されます
scope.ServiceProvider.GetRequiredService<UserDbContext>().Database.Migrate();
実行されます。
以下は生成されたエラーです
System.InvalidOperationException was unhandled by user code HResult=-2146233079 Message=The property 'ClaimsIdentity.BootstrapContext' could not be mapped, because it is of type 'object' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it.
ソース = Microsoft.EntityFrameworkCore StackTrace: Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.PropertyMappingValidationConvention.Apply(InternalModelBuilder modelBuilder) で Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder) で Microsoft.EntityFrameworkCore.Infrastructure. System.Collections.Concurrent.ConcurrentDictionary の ModelSource.CreateModel (DbContext コンテキスト、IConventionSetBuilder コンベンションセットビルダー、IModelValidator バリデーター)2.GetOrAdd(TKey key, Func
2 valueFactory) で Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() で Microsoft.EntityFrameworkCore.Internal.LazyRef`1.get_Value() で Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider) で Microsoft.Extensions. ReportBook の Microsoft.EntityFrameworkCore.DbContext.SetTEntity の Microsoft.EntityFrameworkCore.DbContext.get_Model() の Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider プロバイダー) の DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider プロバイダー、タイプ serviceType)。 C:\Users\Julius\Documents\Projects\School\Development\ReportBook\ReportBook.Auth\Startup の Auth.Startup.InitializeDbTestData(IApplicationBuilder アプリ)。C:\Users\Julius\Documents\Projects\School\Development\ReportBook\ReportBook.Auth\Startup.cs:line 233 の ReportBook.Auth.Startup.Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) の cs:line 166内部例外:
以下は私のスタートアップクラスです
public class Startup
{
private readonly IHostingEnvironment _environment;
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
_environment = env;
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration["Data:UserAccConnection:ConnectionString"];
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "reportbook.auth.pfx"), "");
services.AddCors();
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddMvc();
services.AddDbContext<UserDbContext>(options =>
options.UseSqlServer(connectionString, b => b.MigrationsAssembly(migrationsAssembly)));
// Register the Identity services.
services.AddIdentity<ApplicationUser, UserRole>()
.AddEntityFrameworkStores<UserDbContext, Guid>()
.AddDefaultTokenProviders();
services.AddIdentityServer()
.AddOperationalStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly)))
.AddConfigurationStore(builder => builder.UseSqlServer(connectionString, options => options.MigrationsAssembly(migrationsAssembly)))
.SetSigningCredential(cert)
.AddProfileService<IdentityWithAdditionalClaimsProfileService>();
services.AddTransient<IProfileService, IdentityWithAdditionalClaimsProfileService>();
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
//services.AddTransient<IDatabaseInitializer, DatabaseInitializer>();
}
private static void InitializeDbTestData(IApplicationBuilder app)
{
using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>().Database.Migrate();
scope.ServiceProvider.GetRequiredService<UserDbContext>().Database.Migrate();
var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
if (!context.Clients.Any())
{
foreach (var client in Clients.Get())
{
context.Clients.Add(client.ToEntity());
}
context.SaveChanges();
}
if (!context.Scopes.Any())
{
foreach (var clientSope in Scopes.Get())
{
context.Scopes.Add(clientSope.ToEntity());
}
context.SaveChanges();
}
var userManager = scope.ServiceProvider.GetRequiredService<UserManager<ApplicationUser>>();
if (!userManager.Users.Any())
{
foreach (var applicationUser in Users.Get())
{
foreach (var claim in applicationUser.UserClaims)
{
//ExtendedClaimsProvider.CreateClaim()
applicationUser.Claims.Add(new IdentityUserClaim<Guid>
{
UserId = applicationUser.Id,
ClaimType = claim.Type,
ClaimValue = claim.Value,
});
}
userManager.CreateAsync(applicationUser, "Password123!").Wait();
}
}
}
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseDeveloperExceptionPage();
app.UseStaticFiles();
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod());
app.UseExceptionHandler(
builder =>
{
builder.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
await context.Response.WriteAsync(error.Error.Message).ConfigureAwait(false);
}
});
});
app.UseCsp(options => options.DefaultSources(directive => directive.Self())
.ImageSources(directive => directive.Self()
.CustomSources("*"))
.ScriptSources(directive => directive.Self()
.UnsafeInline())
.StyleSources(directive => directive.Self()
.UnsafeInline()));
app.UseXContentTypeOptions();
app.UseXfo(options => options.Deny());
app.UseXXssProtection(options => options.EnabledWithBlockMode());
InitializeDbTestData(app);
app.UseIdentity();
app.UseIdentityServer();
app.UseMvcWithDefaultRoute();
app.UseMvc();
//databaseInitializer.Seed(app).GetAwaiter().GetResult();
}
}
どんな助けにも感謝します