216 lines
8.6 KiB
C#
Raw Normal View History

using Autofac;
using Autofac.Extensions.DependencyInjection;
using Identity.API.Certificate;
using Identity.API.Configuration;
using Identity.API.Data;
using Identity.API.Models;
using Identity.API.Services;
using IdentityServer4.EntityFramework.DbContexts;
using IdentityServer4.EntityFramework.Mappers;
using IdentityServer4.Services;
2016-11-24 15:31:33 +01:00
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
2016-11-24 15:31:33 +01:00
using Microsoft.EntityFrameworkCore;
using Microsoft.eShopOnContainers.BuildingBlocks;
using Microsoft.eShopOnContainers.Services.Catalog.API.Infrastructure;
2016-11-24 15:31:33 +01:00
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.HealthChecks;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
2016-11-24 15:31:33 +01:00
namespace eShopOnContainers.Identity
{
public class Startup
{
public Startup(IHostingEnvironment env)
2016-11-24 15:31:33 +01:00
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
2016-11-24 15:31:33 +01:00
if (env.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets<Startup>();
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
2016-11-24 15:31:33 +01:00
// This method gets called by the runtime. Use this method to add services to the container.
public IServiceProvider ConfigureServices(IServiceCollection services)
{
2016-11-24 15:31:33 +01:00
// Add framework services.
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.Configure<AppSettings>(Configuration);
2016-11-24 15:31:33 +01:00
services.AddMvc();
if (Configuration.GetValue<string>("IsClusterEnv") == bool.TrueString)
{
services.AddDataProtection(opts =>
{
opts.ApplicationDiscriminator = "eshop.identity";
})
.PersistKeysToRedis(Configuration["DPConnectionString"]);
}
2016-11-24 15:31:33 +01:00
services.AddHealthChecks(checks =>
{
var minutes = 1;
if (int.TryParse(Configuration["HealthCheck:Timeout"], out var minutesParsed))
{
minutes = minutesParsed;
}
checks.AddSqlCheck("Identity_Db", Configuration.GetConnectionString("DefaultConnection"), TimeSpan.FromMinutes(minutes));
});
2016-11-24 15:31:33 +01:00
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
services.AddTransient<ILoginService<ApplicationUser>, EFLoginService>();
services.AddTransient<IRedirectService, RedirectService>();
2016-11-24 15:31:33 +01:00
var connectionString = Configuration.GetConnectionString("DefaultConnection");
var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
2016-11-24 15:31:33 +01:00
// Adds IdentityServer
services.AddIdentityServer(x => x.IssuerUri = "null")
.AddSigningCredential(Certificate.Get())
.AddAspNetIdentity<ApplicationUser>()
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, opts =>
opts.MigrationsAssembly(migrationsAssembly));
})
.AddOperationalStore(options =>
{
options.ConfigureDbContext = builder => builder.UseSqlServer(connectionString, opts =>
opts.MigrationsAssembly(migrationsAssembly));
})
.Services.AddTransient<IProfileService, ProfileService>();
var container = new ContainerBuilder();
container.Populate(services);
return new AutofacServiceProvider(container.Build());
2016-11-24 15:31:33 +01:00
}
// 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();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
2017-09-07 19:18:53 +02:00
var pathBase = Configuration["PATH_BASE"];
if (!string.IsNullOrEmpty(pathBase))
{
loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'");
app.UsePathBase(pathBase);
}
2016-11-24 15:31:33 +01:00
app.UseStaticFiles();
// Make work identity server redirections in Edge and lastest versions of browers. WARN: Not valid in a production environment.
app.Use(async (context, next) =>
{
context.Response.Headers.Add("Content-Security-Policy", "script-src 'unsafe-inline'");
await next();
});
app.UseAuthentication();
2016-11-24 15:31:33 +01:00
// Adds IdentityServer
app.UseIdentityServer();
2016-11-24 15:31:33 +01:00
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
// Store idsrv grant config into db
InitializeGrantStoreAndConfiguration(app).Wait();
//Seed Data
var hasher = new PasswordHasher<ApplicationUser>();
2017-06-20 12:54:32 -07:00
new ApplicationContextSeed(hasher).SeedAsync(app, env, loggerFactory).Wait();
2016-11-24 15:31:33 +01:00
}
private async Task InitializeGrantStoreAndConfiguration(IApplicationBuilder app)
{
//callbacks urls from config:
Dictionary<string, string> clientUrls = new Dictionary<string, string>();
clientUrls.Add("Mvc", Configuration.GetValue<string>("MvcClient"));
clientUrls.Add("Spa", Configuration.GetValue<string>("SpaClient"));
clientUrls.Add("Xamarin", Configuration.GetValue<string>("XamarinCallback"));
clientUrls.Add("LocationsApi", Configuration.GetValue<string>("LocationApiClient"));
clientUrls.Add("MarketingApi", Configuration.GetValue<string>("MarketingApiClient"));
clientUrls.Add("BasketApi", Configuration.GetValue<string>("BasketApiClient"));
clientUrls.Add("OrderingApi", Configuration.GetValue<string>("OrderingApiClient"));
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
serviceScope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
context.Database.Migrate();
if (!context.Clients.Any())
{
foreach (var client in Config.GetClients(clientUrls))
{
await context.Clients.AddAsync(client.ToEntity());
}
await context.SaveChangesAsync();
}
if (!context.IdentityResources.Any())
{
foreach (var resource in Config.GetResources())
{
await context.IdentityResources.AddAsync(resource.ToEntity());
}
await context.SaveChangesAsync();
}
if (!context.ApiResources.Any())
{
foreach (var api in Config.GetApis())
{
await context.ApiResources.AddAsync(api.ToEntity());
}
await context.SaveChangesAsync();
}
}
}
2016-11-24 15:31:33 +01:00
}
}