The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Startup.cs 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Security.Claims;
  6. using IdentityServer4.EntityFramework.DbContexts;
  7. using IdentityServer4.EntityFramework.Mappers;
  8. using Microsoft.AspNetCore.Builder;
  9. using Microsoft.AspNetCore.Hosting;
  10. using Microsoft.AspNetCore.Http;
  11. using Microsoft.AspNetCore.Identity;
  12. using Microsoft.AspNetCore.Mvc;
  13. using Microsoft.EntityFrameworkCore;
  14. using Microsoft.Extensions.Configuration;
  15. using Microsoft.Extensions.DependencyInjection;
  16. using Microsoft.Extensions.Logging;
  17. using Microsoft.Net.Http.Headers;
  18. using Teknik.Configuration;
  19. using Teknik.IdentityServer.Configuration;
  20. using Teknik.IdentityServer.Security;
  21. using Teknik.IdentityServer.Middleware;
  22. using Teknik.Logging;
  23. using Microsoft.AspNetCore.Authorization;
  24. using Teknik.IdentityServer.Models;
  25. using IdentityServer4.Services;
  26. namespace Teknik.IdentityServer
  27. {
  28. public class Startup
  29. {
  30. public Startup(IConfiguration configuration, IHostingEnvironment env)
  31. {
  32. Configuration = configuration;
  33. Environment = env;
  34. }
  35. public IConfiguration Configuration { get; }
  36. public IHostingEnvironment Environment { get; }
  37. public void ConfigureServices(IServiceCollection services)
  38. {
  39. string dataDir = Configuration["ConfigDirectory"];
  40. if (string.IsNullOrEmpty(dataDir))
  41. {
  42. string baseDir = Environment.ContentRootPath;
  43. dataDir = Path.Combine(baseDir, "App_Data");
  44. }
  45. AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
  46. var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
  47. // Create Configuration Singleton
  48. services.AddScoped<Config, Config>(opt => Config.Load(dataDir));
  49. // Build an intermediate service provider
  50. var sp = services.BuildServiceProvider();
  51. // Resolve the services from the service provider
  52. var config = sp.GetService<Config>();
  53. if (config.DevEnvironment)
  54. {
  55. Environment.EnvironmentName = EnvironmentName.Development;
  56. }
  57. else
  58. {
  59. Environment.EnvironmentName = EnvironmentName.Production;
  60. }
  61. services.ConfigureApplicationCookie(options =>
  62. {
  63. options.Cookie.Name = "TeknikAuth";
  64. options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
  65. options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
  66. options.Cookie.Expiration = TimeSpan.FromDays(30);
  67. options.ExpireTimeSpan = TimeSpan.FromDays(30);
  68. });
  69. services.AddHttpsRedirection(options =>
  70. {
  71. options.RedirectStatusCode = (Environment.IsDevelopment()) ? StatusCodes.Status307TemporaryRedirect : StatusCodes.Status308PermanentRedirect;
  72. #if DEBUG
  73. options.HttpsPort = 5050;
  74. #else
  75. options.HttpsPort = 443;
  76. #endif
  77. });
  78. // Sessions
  79. services.AddResponseCaching();
  80. services.AddMemoryCache();
  81. services.AddSession();
  82. // Set the anti-forgery cookie name
  83. services.AddAntiforgery(options =>
  84. {
  85. options.Cookie.Name = "TeknikAuthAntiForgery";
  86. options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
  87. options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
  88. });
  89. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  90. services.AddDbContext<ApplicationDbContext>(builder =>
  91. builder.UseSqlServer(config.DbConnection, sqlOptions => sqlOptions.MigrationsAssembly(migrationsAssembly)));
  92. services.AddIdentity<ApplicationUser, IdentityRole>(options =>
  93. {
  94. options.Password = new PasswordOptions()
  95. {
  96. RequireDigit = false,
  97. RequiredLength = 4,
  98. RequiredUniqueChars = 1,
  99. RequireLowercase = false,
  100. RequireNonAlphanumeric = false,
  101. RequireUppercase = false
  102. };
  103. })
  104. .AddEntityFrameworkStores<ApplicationDbContext>()
  105. .AddDefaultTokenProviders();
  106. services.AddIdentityServer(options =>
  107. {
  108. options.Events.RaiseErrorEvents = true;
  109. options.Events.RaiseInformationEvents = true;
  110. options.Events.RaiseFailureEvents = true;
  111. options.Events.RaiseSuccessEvents = true;
  112. options.UserInteraction.ErrorUrl = "/Error/IdentityError";
  113. options.UserInteraction.ErrorIdParameter = "errorId";
  114. options.Cors.CorsPaths.Add(new PathString("/connect/authorize"));
  115. options.Cors.CorsPaths.Add(new PathString("/connect/endsession"));
  116. options.Cors.CorsPaths.Add(new PathString("/connect/checksession"));
  117. options.Cors.CorsPaths.Add(new PathString("/connect/introspect"));
  118. options.Caching.ClientStoreExpiration = TimeSpan.FromHours(1);
  119. })
  120. .AddOperationalStore(options =>
  121. options.ConfigureDbContext = builder =>
  122. builder.UseSqlServer(config.DbConnection, sqlOptions => sqlOptions.MigrationsAssembly(migrationsAssembly)))
  123. .AddConfigurationStore(options =>
  124. options.ConfigureDbContext = builder =>
  125. builder.UseSqlServer(config.DbConnection, sqlOptions => sqlOptions.MigrationsAssembly(migrationsAssembly)))
  126. .AddConfigurationStoreCache()
  127. .AddAspNetIdentity<ApplicationUser>()
  128. .AddRedirectUriValidator<TeknikRedirectUriValidator>()
  129. .AddDeveloperSigningCredential();
  130. services.AddAuthorization(options =>
  131. {
  132. foreach (var policy in Policies.Get())
  133. {
  134. options.AddPolicy(policy.Name, p =>
  135. {
  136. foreach (var scope in policy.Scopes)
  137. {
  138. p.RequireScope(scope);
  139. }
  140. });
  141. }
  142. });
  143. services.AddAuthentication("Bearer")
  144. .AddIdentityServerAuthentication(options =>
  145. {
  146. options.Authority = config.UserConfig.IdentityServerConfig.Authority;
  147. options.RequireHttpsMetadata = true;
  148. options.ApiName = "auth-api";
  149. });
  150. services.AddTransient<IPasswordHasher<ApplicationUser>, TeknikPasswordHasher>();
  151. services.AddTransient<IProfileService, TeknikProfileService>();
  152. }
  153. public void Configure(IApplicationBuilder app, IHostingEnvironment env, Config config)
  154. {
  155. // Setup the HttpContext
  156. app.UseHttpContextSetup();
  157. // HttpContext Session
  158. app.UseSession(new SessionOptions()
  159. {
  160. IdleTimeout = TimeSpan.FromMinutes(30),
  161. Cookie = new CookieBuilder()
  162. {
  163. Name = "TeknikAuthSession",
  164. SecurePolicy = CookieSecurePolicy.Always,
  165. SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict
  166. }
  167. });
  168. // Use Exception Handling
  169. app.UseErrorHandler(config);
  170. if (env.IsDevelopment())
  171. {
  172. app.UseDeveloperExceptionPage();
  173. }
  174. // Custom Middleware
  175. app.UseBlacklist();
  176. app.UseCORS();
  177. app.UseCSP();
  178. app.UseSecurityHeaders();
  179. // Cache Responses
  180. app.UseResponseCaching();
  181. // Force a HTTPS redirection (301)
  182. app.UseHttpsRedirection();
  183. // Setup static files anc cache them client side
  184. app.UseStaticFiles(new StaticFileOptions
  185. {
  186. OnPrepareResponse = ctx =>
  187. {
  188. ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=" + 31536000;
  189. }
  190. });
  191. InitializeDbTestDataAsync(app, config).Wait();
  192. app.UseIdentityServer();
  193. app.UseMvcWithDefaultRoute();
  194. }
  195. private static async System.Threading.Tasks.Task InitializeDbTestDataAsync(IApplicationBuilder app, Config config)
  196. {
  197. using (var scope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
  198. {
  199. scope.ServiceProvider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
  200. scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>().Database.Migrate();
  201. scope.ServiceProvider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
  202. var context = scope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
  203. if (!context.Clients.Any())
  204. {
  205. foreach (var client in Clients.Get(config))
  206. {
  207. context.Clients.Add(client.ToEntity());
  208. }
  209. context.SaveChanges();
  210. }
  211. if (!context.IdentityResources.Any())
  212. {
  213. foreach (var resource in Resources.GetIdentityResources())
  214. {
  215. context.IdentityResources.Add(resource.ToEntity());
  216. }
  217. context.SaveChanges();
  218. }
  219. if (!context.ApiResources.Any())
  220. {
  221. foreach (var resource in Resources.GetApiResources(config))
  222. {
  223. context.ApiResources.Add(resource.ToEntity());
  224. }
  225. context.SaveChanges();
  226. }
  227. }
  228. }
  229. }
  230. }