public static IIdentityServerBuilder AddOperationalStore( this IIdentityServerBuilder builder, string connectionString, Action <OperationalStoreOptions> storeOptionsAction = null, Action <TokenCleanupOptions> tokenCleanUpOptions = null) { builder.Services.Configure <DatabaseOptions>(dbOptions => { dbOptions.ConnectionString = connectionString; }); builder.Services.AddTransient <IPersistedGrantStore, PersistedGrantStore>(); var storeOptions = new OperationalStoreOptions(); storeOptionsAction?.Invoke(storeOptions); builder.Services.AddSingleton(storeOptions); var tokenCleanupOptions = new TokenCleanupOptions(); tokenCleanUpOptions?.Invoke(tokenCleanupOptions); builder.Services.AddSingleton(tokenCleanupOptions); builder.Services.AddSingleton <TokenCleanup>(); return(builder); }
public static void RegisterDbContexts <TContext>(this IServiceCollection services, IConfigurationRoot configuration) where TContext : DbContext { var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; var operationalStoreOptions = new OperationalStoreOptions(); services.AddSingleton(operationalStoreOptions); var storeOptions = new ConfigurationStoreOptions(); services.AddSingleton(storeOptions); if (configuration["SqlChange:use"].Equals("Mysql", StringComparison.CurrentCultureIgnoreCase)) { #region MySql services.AddDbContext <TContext>(options => options.UseMySql(configuration.GetConnectionString(ConfigurationConsts.MySqlStringKey), optionsSql => optionsSql.MigrationsAssembly(migrationsAssembly))); #endregion } else { #region SQL Server services.AddDbContext <TContext>(options => options.UseSqlServer(configuration.GetConnectionString(ConfigurationConsts.AdminConnectionStringKey), optionsSql => optionsSql.MigrationsAssembly(migrationsAssembly))); #endregion } }
void SetupOperationalStore(OperationalStoreOptions options) { options.ConfigureDbContext = b => b.UseSqlServer(Configuration["Data:AppDb:ConnectionString"], sql => sql.MigrationsAssembly(migrationsAssembly)); options.EnableTokenCleanup = true; }
public IdentityOperationDbContext( DbContextOptions <IdentityOperationDbContext> option, OperationalStoreOptions o, IConfiguration config) : base(option, o) { this._config = config; }
/// <summary> /// Register in memory DbContexts for IdentityServer ConfigurationStore and PersistedGrants, Identity and Logging /// For testing purpose only /// </summary> /// <typeparam name="TConfigurationDbContext"></typeparam> /// <typeparam name="TPersistedGrantDbContext"></typeparam> /// <typeparam name="TLogDbContext"></typeparam> /// <typeparam name="TIdentityDbContext"></typeparam> /// <typeparam name="TAuditLoggingDbContext"></typeparam> /// <typeparam name="TDataProtectionDbContext"></typeparam> /// <param name="services"></param> public static void RegisterDbContextsStaging <TIdentityDbContext, TConfigurationDbContext, TPersistedGrantDbContext, TLogDbContext, TAuditLoggingDbContext, TDataProtectionDbContext>(this IServiceCollection services) where TIdentityDbContext : DbContext where TPersistedGrantDbContext : DbContext, IAdminPersistedGrantDbContext where TConfigurationDbContext : DbContext, IAdminConfigurationDbContext where TLogDbContext : DbContext, IAdminLogDbContext where TAuditLoggingDbContext : DbContext, IAuditLoggingDbContext <AuditLog> where TDataProtectionDbContext : DbContext, IDataProtectionKeyContext { var persistedGrantsDatabaseName = Guid.NewGuid().ToString(); var configurationDatabaseName = Guid.NewGuid().ToString(); var logDatabaseName = Guid.NewGuid().ToString(); var identityDatabaseName = Guid.NewGuid().ToString(); var auditLoggingDatabaseName = Guid.NewGuid().ToString(); var dataProtectionDatabaseName = Guid.NewGuid().ToString(); var operationalStoreOptions = new OperationalStoreOptions(); services.AddSingleton(operationalStoreOptions); var storeOptions = new ConfigurationStoreOptions(); services.AddSingleton(storeOptions); services.AddDbContext <TIdentityDbContext>(optionsBuilder => optionsBuilder.UseInMemoryDatabase(identityDatabaseName)); services.AddDbContext <TPersistedGrantDbContext>(optionsBuilder => optionsBuilder.UseInMemoryDatabase(persistedGrantsDatabaseName)); services.AddDbContext <TConfigurationDbContext>(optionsBuilder => optionsBuilder.UseInMemoryDatabase(configurationDatabaseName)); services.AddDbContext <TLogDbContext>(optionsBuilder => optionsBuilder.UseInMemoryDatabase(logDatabaseName)); services.AddDbContext <TAuditLoggingDbContext>(optionsBuilder => optionsBuilder.UseInMemoryDatabase(auditLoggingDatabaseName)); services.AddDbContext <TDataProtectionDbContext>(optionsBuilder => optionsBuilder.UseInMemoryDatabase(dataProtectionDatabaseName)); }
public static IServiceCollection AddAdminContext(this IServiceCollection services, Action <DbContextOptionsBuilder> optionsAction, JpDatabaseOptions options = null) { if (options == null) { options = new JpDatabaseOptions(); } RegisterDatabaseServices(services); var operationalStoreOptions = new OperationalStoreOptions(); services.AddSingleton(operationalStoreOptions); var storeOptions = new ConfigurationStoreOptions(); services.AddSingleton(storeOptions); services.AddDbContext <JPProjectAdminUIContext>(optionsAction); services.AddDbContext <EventStoreContext>(optionsAction); DbMigrationHelpers.CheckDatabases(services.BuildServiceProvider(), options).Wait(); return(services); }
public async Task Should_Remove_Expired_Grants_In_Batches(TestDatabase testDb) { using (var session = testDb.OpenSession()) { for (var i = 0; i < 5; i++) { await session.SaveAsync(new Models.PersistedGrant { Key = Guid.NewGuid().ToString(), ClientId = "test-app", Type = "reference", SubjectId = (42 + i).ToString(), Expiration = DateTime.UtcNow.AddDays(-3), Data = $"testdata {i}" }.ToEntity()); } await session.FlushAsync(); } var options = new OperationalStoreOptions() { TokenCleanupBatchSize = 2 }; await CreateTokenCleanupServiceSut(testDb, options).RemoveExpiredGrantsAsync(); using (var session = testDb.OpenSession()) { (await session.QueryOver <PersistedGrant>().RowCountAsync()).Should().Be(0); } await CleanupTestDataAsync(testDb); }
public async Task Should_Remove_Expired_Device_Codes_In_Batches(TestDatabase testDb) { using (var session = testDb.OpenSession()) { for (var i = 0; i < 5; i++) { await session.SaveAsync(new DeviceFlowCodes { DeviceCode = Guid.NewGuid().ToString(), ID = $"1234{i}", ClientId = "test-app", SubjectId = (42 + i).ToString(), CreationTime = DateTime.UtcNow.AddDays(-4), Expiration = DateTime.UtcNow.AddDays(-3), Data = $"testdata {i}" }); } await session.FlushAsync(); } var options = new OperationalStoreOptions() { TokenCleanupBatchSize = 2 }; await CreateTokenCleanupServiceSut(testDb, options).RemoveExpiredGrantsAsync(); using (var session = testDb.OpenSession()) { (await session.QueryOver <DeviceFlowCodes>().RowCountAsync()).Should().Be(0); } await CleanupTestDataAsync(testDb); }
public IActionResult Get() { var options = new DbContextOptions <PersistedGrantDbContext>(); var store = new OperationalStoreOptions(); using (var ctx = new PersistedGrantDbContext(options, store)) { ctx.Add <Client>(new Client { ClientId = "c1", ClientSecrets = new List <ClientSecret> { new ClientSecret() { Type = "SharedSecret", Value = "secret" } }, AllowedGrantTypes = new List <ClientGrantType> { new ClientGrantType { GrantType = "client_id" } }, AllowedScopes = new List <ClientScope> { new ClientScope { Scope = "api1" } } }); ctx.SaveChanges(); } return(Ok()); }
static void Main(string[] args) { DbContextOptionsBuilder optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>().UseInMemoryDatabase("SQRS"); OperationalStoreOptions storeOptions = new OperationalStoreOptions(); IOptions <OperationalStoreOptions> optionParameter = Options.Create(storeOptions); dbContext = new ApplicationDbContext(optionsBuilder.Options, optionParameter); PreLoadTypeMappings(); PreLoadCreateExcludedProperties(); PreLoadUpdateExcludedProperties(); // loading enetites assembly Assembly assembly = Assembly.Load(enities_assembly); Type[] entityList = assembly .GetTypes() .Where(t => t.IsClass && t.Namespace == entities_namespace && !t.IsInterface && !t.IsAbstract) .ToArray(); foreach (Type entity in entityList.Where(t => t.BaseType == typeof(AuditableEntity))) { GenerateCreateCommand(entity); GenerateCreateCommandValidator(entity); GenerateUpdateCommand(entity); GenerateUpdateCommandValidator(entity); GenerateDeleteCommand(entity); } }
/// <summary> /// Register in memory DbContexts for IdentityServer ConfigurationStore and PersistedGrants, Identity and Logging /// For testing purpose only /// </summary> /// <typeparam name="TConfigurationDbContext"></typeparam> /// <typeparam name="TPersistedGrantDbContext"></typeparam> /// <typeparam name="TLogDbContext"></typeparam> /// <typeparam name="TIdentityDbContext"></typeparam> /// <param name="services"></param> public static void RegisterDbContextsStaging <TIdentityDbContext, TConfigurationDbContext, TPersistedGrantDbContext, TLogDbContext>(this IServiceCollection services, IConfigurationRoot configuration) where TIdentityDbContext : MainContext where TPersistedGrantDbContext : DbContext, IAdminPersistedGrantDbContext where TConfigurationDbContext : DbContext, IAdminConfigurationDbContext where TLogDbContext : DbContext, IAdminLogDbContext { var persistedGrantsDatabaseName = Guid.NewGuid().ToString(); var configurationDatabaseName = Guid.NewGuid().ToString(); var logDatabaseName = Guid.NewGuid().ToString(); var identityDatabaseName = Guid.NewGuid().ToString(); var operationalStoreOptions = new OperationalStoreOptions(); services.AddSingleton(operationalStoreOptions); var storeOptions = new ConfigurationStoreOptions(); services.AddSingleton(storeOptions); // Config DB for identity //TODO: services.AddMainContext(configuration.GetConnectionString(ModelConstants.SantillanaConnectContext)); //services.AddDbContext<TIdentityDbContext>(optionsBuilder => optionsBuilder.UseInMemoryDatabase(identityDatabaseName)); services.AddDbContext <TPersistedGrantDbContext>(optionsBuilder => optionsBuilder.UseInMemoryDatabase(persistedGrantsDatabaseName)); services.AddDbContext <TConfigurationDbContext>(optionsBuilder => optionsBuilder.UseInMemoryDatabase(configurationDatabaseName)); services.AddDbContext <TLogDbContext>(optionsBuilder => optionsBuilder.UseInMemoryDatabase(logDatabaseName)); }
public static void RegisterDbContexts(this IServiceCollection services, IConfigurationRoot configuration) { var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; var operationalStoreOptions = new OperationalStoreOptions(); services.AddSingleton(operationalStoreOptions); var storeOptions = new ConfigurationStoreOptions(); services.AddSingleton(storeOptions); services.AddDbContext <AdminDbContext>(options => options.UseMySql( configuration.GetConnectionString(ConfigurationConsts.AdminConnectionStringKeyIdentity), sql => { sql.MigrationsAssembly(migrationsAssembly); sql.ServerVersion(new Version(5, 7), ServerType.MySql); } )); services.AddDbContext <ConfigurationDbContext>(options => options.UseMySql( configuration.GetConnectionString(ConfigurationConsts.AdminConnectionStringKeyConfiguration), sql => { sql.MigrationsAssembly(migrationsAssembly); sql.ServerVersion(new Version(5, 7), ServerType.MySql); } )); }
/// <summary> /// Adds NHibernate core components to the DI system. /// </summary> /// <param name="builder">The builder.</param> /// <param name="databaseConfiguration">NHibernate database configuration.</param> /// <param name="configurationStoreOptions">Configuration store options (needed to configure NHibernate mappings).</param> /// <param name="operationalStoreOptions">Operational store options (needed to configure NHibernate mappings).</param> private static IIdentityServerBuilder AddNHibernatePersistenceSupport( this IIdentityServerBuilder builder, NHibernate.Cfg.Configuration databaseConfiguration, ConfigurationStoreOptions configurationStoreOptions, OperationalStoreOptions operationalStoreOptions) { // Adds NHibernate mappings databaseConfiguration.AddConfigurationStoreMappings(configurationStoreOptions); databaseConfiguration.AddOperationalStoreMappings(operationalStoreOptions); //We need this to quote fields named with reserved keyword SchemaMetadataUpdater.QuoteTableAndColumns(databaseConfiguration, Dialect.GetDialect(databaseConfiguration.Properties)); // Registers NHibernate components builder.Services.AddSingleton(databaseConfiguration.BuildSessionFactory()); builder.Services.AddScoped(provider => { var factory = provider.GetService <ISessionFactory>(); return(factory.OpenSession()); }); builder.Services.AddScoped(provider => { var factory = provider.GetService <ISessionFactory>(); return(factory.OpenStatelessSession()); }); return(builder); }
/// <summary> /// Scripts the database objects creation for storing IdentityServer data. /// </summary> /// <param name="scriptFileName">Output file name</param> /// <param name="configuration">NHibernate Configuration object that represents the database configuration to script.</param> /// <param name="configurationStoreOptions">Options for configuration store.</param> /// <param name="operationalStoreOptions">Options for operational store.</param> /// <remarks> /// Configuration store options and operational store options are needed to detect the schema for each database object. /// </remarks> public static void CreateSchemaScriptForDatabase( string scriptFileName, Configuration configuration, ConfigurationStoreOptions configurationStoreOptions, OperationalStoreOptions operationalStoreOptions) { if (configurationStoreOptions == null) { throw new ArgumentNullException(nameof(configurationStoreOptions)); } if (operationalStoreOptions == null) { throw new ArgumentNullException(nameof(operationalStoreOptions)); } configuration.AddConfigurationStoreMappings(configurationStoreOptions); configuration.AddOperationalStoreMappings(operationalStoreOptions); var dialect = Dialect.GetDialect(configuration.Properties); SchemaMetadataUpdater.QuoteTableAndColumns(configuration, dialect); new SchemaExport(configuration) .SetOutputFile(scriptFileName) .SetDelimiter(";") .Execute(true, false, false); }
/// <summary> /// Adds NHibernate core components to the DI system. /// </summary> /// <param name="builder">The builder.</param> /// <param name="databaseConfiguration">NHibernate database configuration.</param> /// <param name="configurationStoreOptions">Configuration store options (needed to configure NHibernate mappings).</param> /// <param name="operationalStoreOptions">Operational store options (needed to configure NHibernate mappings).</param> private static IIdentityServerBuilder AddNHibernatePersistenceSupport( this IIdentityServerBuilder builder, NHibernate.Cfg.Configuration databaseConfiguration, ConfigurationStoreOptions configurationStoreOptions, OperationalStoreOptions operationalStoreOptions) { // Adds NHibernate mappings databaseConfiguration.AddConfigurationStoreMappings(configurationStoreOptions); databaseConfiguration.AddOperationalStoreMappings(operationalStoreOptions); // Registers NHibernate components builder.Services.AddSingleton(databaseConfiguration.BuildSessionFactory()); builder.Services.AddScoped(provider => { var factory = provider.GetService <ISessionFactory>(); return(factory.OpenSession()); }); builder.Services.AddScoped(provider => { var factory = provider.GetService <ISessionFactory>(); return(factory.OpenStatelessSession()); }); return(builder); }
/// <summary> /// Configures EF implementation of IPersistedGrantStore with IdentityServer. /// </summary> /// <typeparam name="TContext">The IPersistedGrantDbContext to use.</typeparam> /// <param name="builder">The builder.</param> /// <param name="storeOptionsAction">The store options action.</param> /// <returns></returns> public static IIdentityServerBuilder AddOperationalStore <TContext>( this IIdentityServerBuilder builder, Action <OperationalStoreOptions> storeOptionsAction = null) where TContext : DbContext, IPersistedGrantDbContext { builder.Services.AddSingleton <TokenCleanup>(); builder.Services.AddSingleton <IHostedService, TokenCleanupHost>(); var storeOptions = new OperationalStoreOptions(); builder.Services.AddSingleton(storeOptions); storeOptionsAction?.Invoke(storeOptions); if (storeOptions.ResolveDbContextOptions != null) { builder.Services.AddDbContext <TContext>(storeOptions.ResolveDbContextOptions); } else { builder.Services.AddDbContext <TContext>(dbCtxBuilder => { storeOptions.ConfigureDbContext?.Invoke(dbCtxBuilder); }); } builder.Services.AddScoped <IPersistedGrantDbContext, TContext>(); builder.Services.AddTransient <IPersistedGrantStore, PersistedGrantStore>(); return(builder); }
/// <summary> /// Adds operational DbContext to the DI system. /// </summary> /// <typeparam name="TContext">The IPersistedGrantDbContext to use.</typeparam> /// <param name="services"></param> /// <param name="storeOptionsAction">The store options action.</param> /// <returns></returns> public static IServiceCollection AddOperationalDbContext <TContext>(this IServiceCollection services, Action <OperationalStoreOptions> storeOptionsAction = null) where TContext : DbContext, IPersistedGrantDbContext { var storeOptions = new OperationalStoreOptions(); services.AddSingleton(storeOptions); storeOptionsAction?.Invoke(storeOptions); if (storeOptions.ResolveDbContextOptions != null) { services.AddDbContext <TContext>(storeOptions.ResolveDbContextOptions); } else { services.AddDbContext <TContext>(dbCtxBuilder => { storeOptions.ConfigureDbContext?.Invoke(dbCtxBuilder); }); } services.AddScoped <IPersistedGrantDbContext, TContext>(); services.AddTransient <TokenCleanupService>(); return(services); }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.Configure <EntityFrameworkConnectionOptions>( Configuration.GetSection("EntityFrameworkConnectionOptions")); var appOptions = Configuration .GetSection("AppOptions") .Get <AppOptions>(); switch (appOptions.DatabaseType) { default: services.AddInMemoryDbContextOptionsProvider(); break; case AppOptions.DatabaseTypes.Postgres: break; case AppOptions.DatabaseTypes.SqlServer: services.AddSqlServerDbContextOptionsProvider(); break; } services.AddDbContextTenantServices(); var options = new ConfigurationStoreOptions(); services.AddSingleton(options); var operationalStoreOptions = new OperationalStoreOptions(); services.AddSingleton(operationalStoreOptions); }
/// <summary> /// Register shared DbContext for IdentityServer ConfigurationStore and PersistedGrants, Identity and Logging /// Configure the connection string in AppSettings.json - use AdminConnection key /// </summary> /// <typeparam name="TContext"></typeparam> /// <param name="services"></param> /// <param name="configuration"></param> public static void RegisterDbContexts <TContext>(this IServiceCollection services, IConfigurationRoot configuration) where TContext : DbContext { var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; var operationalStoreOptions = new OperationalStoreOptions(); services.AddSingleton(operationalStoreOptions); var storeOptions = new ConfigurationStoreOptions(); services.AddSingleton(storeOptions); services.AddDbContext <TContext>(options => { var provider = configuration.GetValue <string>(ConfigurationConsts.DatabaseProvider); var connectionString = configuration.GetConnectionString(ConfigurationConsts.AdminConnectionStringKey); if ("Sqlite".Equals(provider, StringComparison.OrdinalIgnoreCase)) { options.UseSqlite(connectionString); } else { options.UseSqlServer(connectionString); } }); }
public UserIdentityDbContext(DbContextOptions <UserIdentityDbContext> options, ConfigurationStoreOptions storeOptions, OperationalStoreOptions operationalOptions) : base(options) { _storeOptions = storeOptions; _operationalOptions = operationalOptions; }
public PersistedGrantDbContext(FirestoreOptions options, OperationalStoreOptions storeOptions) : base(options) { Schema = Database.Document($"{Constants.IdentityServer}/{storeOptions.Schema}"); PersistedGrants = Schema.Collection(storeOptions.PersistedGrants); DeviceFlowCodes = Schema.Collection(storeOptions.DeviceFlowCodes); }
public DeviceFlowStore(IAsyncDocumentSession session, IPersistentGrantSerializer serializer, ILogger <DeviceFlowStore> logger, OperationalStoreOptions options) { Session = session ?? throw new ArgumentNullException(nameof(session)); Serializer = serializer; Logger = logger; Options = options; }
public AdminDbContext(DbContextOptions <AdminDbContext> options, ConfigurationStoreOptions storeOptions, OperationalStoreOptions operationalOptions) : base(options) { _storeOptions = storeOptions; _operationalOptions = operationalOptions; }
public JPProjectAdminUIContext(DbContextOptions <JPProjectAdminUIContext> options, ConfigurationStoreOptions storeOptions, OperationalStoreOptions operationalOptions ) : base(options) { _storeOptions = storeOptions; _operationalOptions = operationalOptions; }
public PersistedGrantDbContext(DbContextOptions <PersistedGrantDbContext> options, OperationalStoreOptions storeOptions) : base(options) { if (storeOptions == null) { throw new ArgumentNullException(nameof(storeOptions)); } this._storeOptions = storeOptions; }
public static OperationalStoreOptions Build() { var options = new OperationalStoreOptions { //此处,可以IdentityServer4所使用的表名称进行自定义设置(TableConfiguration类型属性); }; return(options); }
public IdentityServerPersistedGrantDbContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder <IdentityServerPersistedGrantDbContext>(); optionsBuilder.UseSqlite("Filename=c://tmp/PersistedGrant.db"); var op = new OperationalStoreOptions(); return(new IdentityServerPersistedGrantDbContext(optionsBuilder.Options, op)); }
public PersistedGrantDbContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder <PersistedGrantDbContext>(); optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=aspnet-IdentityServerSystemOpenID2;Trusted_Connection=True;MultipleActiveResultSets=true", b => b.MigrationsAssembly("IdentityServerSystem")); var configStoreOptions = new OperationalStoreOptions(); return(new PersistedGrantDbContext(optionsBuilder.Options, configStoreOptions)); }
public TokenCleanupHost(OperationalStoreOptions options, TokenCleanup tokenCleanup) { _options = options; _tokenCleanup = tokenCleanup; if (_options.EnableTokenCleanup) { _tokenCleanup.SetInterval(options.TokenCleanupInterval); } }
public void Load(OperationalStoreOptions options) { var props = options.GetType().GetProperties(); foreach (var prop in props) { prop.SetValue(options, prop.GetValue(this)); } }