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 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Identity;
  7. using Microsoft.AspNetCore.Hosting;
  8. using Microsoft.AspNetCore.Http;
  9. using Microsoft.AspNetCore.HttpsPolicy;
  10. using Microsoft.AspNetCore.Mvc;
  11. using Microsoft.EntityFrameworkCore;
  12. using Teknik.Data;
  13. using Teknik.Utilities;
  14. using Microsoft.Extensions.Configuration;
  15. using Microsoft.Extensions.DependencyInjection;
  16. using Teknik.Logging;
  17. using System.IO;
  18. using Microsoft.Extensions.Logging;
  19. using Teknik.Configuration;
  20. using Teknik.Middleware;
  21. using Microsoft.AspNetCore.ResponseCompression;
  22. using System.IO.Compression;
  23. using System.Text;
  24. using Microsoft.AspNetCore.Authentication.Cookies;
  25. using IdentityServer4.Models;
  26. using Teknik.Areas.Accounts;
  27. using Microsoft.AspNetCore.Authentication.OpenIdConnect;
  28. using Teknik.Security;
  29. using Teknik.Attributes;
  30. using Teknik.Filters;
  31. using Microsoft.Net.Http.Headers;
  32. namespace Teknik
  33. {
  34. public class Startup
  35. {
  36. public Startup(IConfiguration configuration, IHostingEnvironment env)
  37. {
  38. Configuration = configuration;
  39. Environment = env;
  40. }
  41. public IConfiguration Configuration { get; }
  42. public IHostingEnvironment Environment { get; }
  43. // This method gets called by the runtime. Use this method to add services to the container.
  44. public void ConfigureServices(IServiceCollection services)
  45. {
  46. string baseDir = Environment.ContentRootPath;
  47. string dataDir = Path.Combine(baseDir, "App_Data");
  48. AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
  49. // Setup IIS
  50. services.Configure<IISOptions>(options =>
  51. {
  52. options.ForwardClientCertificate = false;
  53. options.AutomaticAuthentication = false;
  54. });
  55. // HTTP Context
  56. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  57. // Create Configuration Singleton
  58. services.AddScoped<Config, Config>(opt => Config.Load(dataDir));
  59. // Add Tracking Filter scopes
  60. //services.AddScoped<TrackDownload>();
  61. //services.AddScoped<TrackLink>();
  62. //services.AddScoped<TrackPageView>();
  63. // Create the Database Context
  64. services.AddDbContext<TeknikEntities>(options => options
  65. .UseLazyLoadingProxies()
  66. .UseSqlServer(Configuration.GetConnectionString("TeknikEntities")), ServiceLifetime.Transient);
  67. // Cookie Policies
  68. services.Configure<CookiePolicyOptions>(options =>
  69. {
  70. // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  71. options.CheckConsentNeeded = context => true;
  72. options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
  73. });
  74. // Setup Authentication Service
  75. services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
  76. .AddCookie(options =>
  77. {
  78. options.Cookie.Domain = null;
  79. options.Cookie.Name = "TeknikAuth";
  80. options.LoginPath = "/User/User/Login";
  81. options.LogoutPath = "/User/User/Logout";
  82. options.EventsType = typeof(TeknikCookieAuthenticationEvents);
  83. });
  84. services.AddScoped<TeknikCookieAuthenticationEvents>();
  85. // Compression Response
  86. services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
  87. services.AddResponseCompression(options => {
  88. options.Providers.Add<GzipCompressionProvider>();
  89. });
  90. services.AddHttpsRedirection(options =>
  91. {
  92. options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
  93. });
  94. // Sessions
  95. services.AddResponseCaching();
  96. services.AddMemoryCache();
  97. services.AddSession();
  98. // Set the anti-forgery cookie name
  99. services.AddAntiforgery(options => options.Cookie.Name = "TeknikAntiForgery");
  100. // Core MVC
  101. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  102. //services.AddIdentityServer()
  103. // .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>();
  104. }
  105. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  106. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, TeknikEntities dbContext, Config config)
  107. {
  108. // Create and Migrate the database
  109. dbContext.Database.Migrate();
  110. // Initiate Logging
  111. loggerFactory.AddLogger(config);
  112. // Setup the HttpContext
  113. app.UseHttpContextSetup();
  114. // HttpContext Session
  115. app.UseSession(new SessionOptions()
  116. {
  117. IdleTimeout = TimeSpan.FromMinutes(30),
  118. Cookie = new CookieBuilder()
  119. {
  120. Domain = null,
  121. Name = "TeknikSession"
  122. }
  123. });
  124. // Use Exception Handling
  125. app.UseErrorHandler(config);
  126. if (env.IsDevelopment())
  127. {
  128. app.UseBrowserLink();
  129. //app.UseDeveloperExceptionPage();
  130. app.UseDatabaseErrorPage();
  131. }
  132. // Performance Monitor the entire request
  133. app.UsePerformanceMonitor();
  134. // Custom Middleware
  135. app.UseBlacklist();
  136. app.UseCORS();
  137. app.UseCSP();
  138. app.UseSecurityHeaders();
  139. // Cache Responses
  140. app.UseResponseCaching();
  141. // Force a HTTPS redirection (301)
  142. app.UseHttpsRedirection();
  143. // Setup static files anc cache them client side
  144. app.UseStaticFiles(new StaticFileOptions
  145. {
  146. OnPrepareResponse = ctx =>
  147. {
  148. const int durationInSeconds = 60 * 60 * 24;
  149. ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=" + durationInSeconds;
  150. }
  151. });
  152. // Enable Cookie Policy
  153. app.UseCookiePolicy();
  154. // Authorize all the things!
  155. app.UseAuthentication();
  156. // And finally, let's use MVC
  157. app.UseMvc(routes =>
  158. {
  159. routes.BuildRoutes(config);
  160. });
  161. }
  162. }
  163. }