public void ConfigureServices(IConfiguration configuration, IServiceCollection services) { string appDbContextConnectionString = configuration.GetConnectionString("AppDbContext"); // Override with Azure connection string if exists var azureConnectionStringEnvironmentVariable = configuration["AzureConnectionStringEnvironmentVariable"]; if (!string.IsNullOrEmpty(azureConnectionStringEnvironmentVariable)) { appDbContextConnectionString = Environment.GetEnvironmentVariable(azureConnectionStringEnvironmentVariable); appDbContextConnectionString = AzureMySQL.ToMySQLStandard(appDbContextConnectionString); } var provider = configuration["AppDbProvider"]; if (string.IsNullOrEmpty(provider)) { provider = "sqlite"; } switch (provider.ToLower()) { case "mssql": services.AddDbContext <AppDbContext>(options => options.UseSqlServer(appDbContextConnectionString, optionsBuilder => optionsBuilder.MigrationsAssembly("Banico.EntityFrameworkCore")), ServiceLifetime.Scoped); break; case "mysql": services.AddDbContext <AppDbContext>(options => options.UseMySql(appDbContextConnectionString, optionsBuilder => optionsBuilder.MigrationsAssembly("Banico.EntityFrameworkCore")), ServiceLifetime.Scoped); break; case "sqlite": if (string.IsNullOrEmpty(appDbContextConnectionString)) { var connectionStringBuilder = new Microsoft.Data.Sqlite.SqliteConnectionStringBuilder { DataSource = "banico.db" }; appDbContextConnectionString = connectionStringBuilder.ToString(); } services.AddDbContext <AppDbContext>(options => options.UseSqlite(appDbContextConnectionString, optionsBuilder => optionsBuilder.MigrationsAssembly("Banico.EntityFrameworkCore")), ServiceLifetime.Scoped); break; } services.AddOptions(); services.AddScoped <IInviteRepository, InviteRepository>(); services.AddScoped <ISectionRepository, SectionRepository>(); services.AddScoped <ISectionItemRepository, SectionItemRepository>(); services.AddScoped <IContentItemRepository, ContentItemRepository>(); services.AddScoped <IConfigRepository, ConfigRepository>(); }
public void ToMySQLStandard_NonMySQLStandard_MySQLStandard() { var inputCS = "Database=localdb;Data Source=127.0.0.1:54068;User Id=azure;Password=kedzior"; var expectedCS = "Database=localdb;Port=54068;Pwd=kedzior;Server=127.0.0.1;Uid=azure"; var actualCS = AzureMySQL.ToMySQLStandard(inputCS); Assert.Equal(expectedCS, actualCS); }
public void ToMySQLStandard_ConnStringWhiteSpace_ThrowsArgumentException() { string inputCS = " "; var expectedMessage = "Connection String is empty."; var exception = Assert.Throws <ArgumentException>(() => AzureMySQL.ToMySQLStandard(inputCS)); Assert.Equal(expectedMessage, exception.Message); }
public void ToMySQLStandard_PortIncluded_PortNotDuplicate() { var inputCS = "Data Source=127.0.0.1;Port=3306;Database=localdb;Password=kedzior;User Id=azure"; var expectedCS = "Database=localdb;Port=3306;Pwd=kedzior;Server=127.0.0.1;Uid=azure"; var actualCS = AzureMySQL.ToMySQLStandard(inputCS); Assert.Equal(expectedCS, actualCS); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); string connectionString = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb"); services.AddDbContext <ApplicationDbContext>(options => options.UseMySql(AzureMySQL.ToMySQLStandard(connectionString))); // Automatically perform database migration services.BuildServiceProvider().GetService <ApplicationDbContext>().Database.Migrate(); services.AddDefaultIdentity <IdentityUser>() .AddEntityFrameworkStores <ApplicationDbContext>(); services.AddAuthentication().AddGoogle(googleOptions => { googleOptions.ClientId = Configuration["Authentication:Google:ClientId"]; googleOptions.ClientSecret = Configuration["Authentication:Google:ClientSecret"]; }); services.AddAuthentication().AddFacebook(facebookOptions => { facebookOptions.AppId = Configuration["Authentication:Facebook:AppId"]; facebookOptions.AppSecret = Configuration["Authentication:Facebook:AppSecret"]; }); services.AddRouting(options => { options.LowercaseUrls = true; }); services.AddSingleton(typeof(IHttpContextAccessor), typeof(HttpContextAccessor)); services.AddMvc() .AddRazorPagesOptions(o => o.Conventions.AddAreaFolderRouteModelConvention("Identity", "/Account/", model => { foreach (var selector in model.Selectors) { var attributeRouteModel = selector.AttributeRouteModel; attributeRouteModel.Order = -1; attributeRouteModel.Template = attributeRouteModel.Template.Remove(0, "Identity".Length); } })) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddCookieTempDataProvider(); services.AddProgressiveWebApp(); }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (_isMigration) { string connectionString = _configuration.GetConnectionString("AppDbContext"); // Override with Azure connection string if exists var azureConnectionStringEnvironmentVariable = _configuration["AzureConnectionStringEnvironmentVariable"]; if (!string.IsNullOrEmpty(azureConnectionStringEnvironmentVariable)) { connectionString = Environment.GetEnvironmentVariable(azureConnectionStringEnvironmentVariable); connectionString = AzureMySQL.ToMySQLStandard(connectionString); } var provider = _configuration["AppDbProvider"]; if (string.IsNullOrEmpty(provider)) { provider = "sqlite"; } switch (provider.ToLower()) { case "mssql": optionsBuilder.UseSqlServer(connectionString); break; case "mysql": optionsBuilder.UseMySql(connectionString); break; case "sqlite": if (string.IsNullOrEmpty(connectionString)) { var connectionStringBuilder = new Microsoft.Data.Sqlite.SqliteConnectionStringBuilder { DataSource = "banico.db" }; connectionString = connectionStringBuilder.ToString(); } optionsBuilder.UseSqlite(connectionString); break; } } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddHttpClient(); services.AddDbContext <ApplicationDbContext>(options => { if (Configuration.GetSection("AppSettings").GetValue <bool>("MySQLDatabase")) { string envConnectionString = Environment.GetEnvironmentVariable("MYSQLCONNSTR_localdb"); if (!String.IsNullOrEmpty(envConnectionString)) { options.UseMySql(AzureMySQL.ToMySQLStandard(envConnectionString)); } else { options.UseMySql(Configuration.GetConnectionString("DefaultConnection")); } } else { options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")); } }); services.AddIdentity <ApplicationUser, IdentityRole>() .AddErrorDescriber <LocalizedIdentityErrorDescriber>() .AddEntityFrameworkStores <ApplicationDbContext>(); services.Configure <ApplicationSettings>(Configuration.GetSection("AppSettings")); services.Configure <IdentityOptions>(options => { // Password settings. options.Password.RequireDigit = true; options.Password.RequireLowercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 6; options.Password.RequiredUniqueChars = 1; // Lockout settings. options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5); options.Lockout.MaxFailedAccessAttempts = 5; options.Lockout.AllowedForNewUsers = true; // User settings. options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+"; options.User.RequireUniqueEmail = true; }); services.AddTransient <AdminSeeder>(); services.ConfigureApplicationCookie(options => { options.Events = new CookieAuthenticationEvents() { OnRedirectToLogin = redirectContext => { var uri = redirectContext.RedirectUri; UriHelper.FromAbsolute(uri, out var scheme, out var host, out var path, out var query, out var fragment); uri = UriHelper.BuildAbsolute(scheme, host, path, default, default, new FragmentString("#game"));
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. string appIdentityDbContextConnectionString = Configuration.GetConnectionString("AppIdentityDbContext"); // Override with Azure connection string if exists var azureConnectionStringEnvironmentVariable = this.Configuration["AzureConnectionStringEnvironmentVariable"]; if (!string.IsNullOrEmpty(azureConnectionStringEnvironmentVariable)) { appIdentityDbContextConnectionString = Environment.GetEnvironmentVariable(azureConnectionStringEnvironmentVariable); appIdentityDbContextConnectionString = AzureMySQL.ToMySQLStandard(appIdentityDbContextConnectionString); } var provider = Configuration["AppIdentityDBProvider"]; if (string.IsNullOrEmpty(provider)) { provider = "sqlite"; } switch (provider.ToLower()) { case "mssql": services.AddDbContext <AppIdentityDbContext>(options => options.UseSqlServer(appIdentityDbContextConnectionString, optionsBuilder => optionsBuilder.MigrationsAssembly("Banico.Identity"))); break; case "mysql": services.AddDbContext <AppIdentityDbContext>(options => options.UseMySql(appIdentityDbContextConnectionString, optionsBuilder => optionsBuilder.MigrationsAssembly("Banico.Identity"))); break; case "sqlite": if (string.IsNullOrEmpty(appIdentityDbContextConnectionString)) { var connectionStringBuilder = new Microsoft.Data.Sqlite.SqliteConnectionStringBuilder { DataSource = "banico-identity.db" }; appIdentityDbContextConnectionString = connectionStringBuilder.ToString(); } services.AddDbContext <AppIdentityDbContext>(options => options.UseSqlite(appIdentityDbContextConnectionString, optionsBuilder => optionsBuilder.MigrationsAssembly("Banico.Identity"))); break; } services.AddSingleton <IJwtFactory, JwtFactory>(); // Register the ConfigurationBuilder instance of FacebookAuthSettings services.Configure <FacebookAuthSettings>(Configuration.GetSection(nameof(FacebookAuthSettings))); // jwt wire up // Get options from app settings var jwtAppSettingOptions = Configuration.GetSection(nameof(JwtIssuerOptions)); // Configure JwtIssuerOptions services.Configure <JwtIssuerOptions>(options => { options.Issuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)]; options.Audience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)]; options.SigningCredentials = new SigningCredentials(_signingKey, SecurityAlgorithms.HmacSha256); }); var tokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)], ValidateAudience = true, ValidAudience = jwtAppSettingOptions[nameof(JwtIssuerOptions.Audience)], ValidateIssuerSigningKey = true, IssuerSigningKey = _signingKey, RequireExpirationTime = false, ValidateLifetime = true, ClockSkew = TimeSpan.Zero }; services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(configureOptions => { configureOptions.ClaimsIssuer = jwtAppSettingOptions[nameof(JwtIssuerOptions.Issuer)]; configureOptions.TokenValidationParameters = tokenValidationParameters; configureOptions.SaveToken = true; }); // api user claim policy // services.AddAuthorization(options => // { // options.AddPolicy("ApiUser", policy => policy.RequireClaim(Constants.Strings.JwtClaimIdentifiers.Rol, Constants.Strings.JwtClaims.ApiAccess)); // }); // add identity var builder = services.AddIdentity <AppUser, AppRole>(o => { // configure identity options o.Password.RequireDigit = false; o.Password.RequireLowercase = false; o.Password.RequireUppercase = false; o.Password.RequireNonAlphanumeric = false; o.Password.RequiredLength = 6; o.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; o.User.RequireUniqueEmail = true; }) .AddSignInManager <SignInManager <AppUser> >() .AddEntityFrameworkStores <AppIdentityDbContext>() .AddDefaultTokenProviders(); services.AddAuthorization(options => { options.AddPolicy("SuperAdmin", policy => policy.Requirements.Add(new SuperAdminRequirement())); options.AddPolicy("Admin", policy => policy.Requirements.Add(new AdminRequirement())); }); services.AddSingleton <IAuthorizationHandler, AdminHandler>(); services.AddSingleton <IAuthorizationHandler, SuperAdminHandler>(); services.ConfigureApplicationCookie(options => { options.Events = new CookieAuthenticationEvents { OnRedirectToAccessDenied = ReplaceRedirector(HttpStatusCode.Forbidden, context => options.Events.RedirectToAccessDenied(context)), OnRedirectToLogin = ReplaceRedirector(HttpStatusCode.Unauthorized, context => options.Events.RedirectToLogin(context)) }; }); services.AddAutoMapper(); // builder = new IdentityBuilder(builder.UserType, typeof(AppRole), builder.Services); }