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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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.Cookie.SecurePolicy = CookieSecurePolicy.Always;
  81. options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
  82. options.LoginPath = "/User/User/Login";
  83. options.LogoutPath = "/User/User/Logout";
  84. options.EventsType = typeof(TeknikCookieAuthenticationEvents);
  85. });
  86. services.AddScoped<TeknikCookieAuthenticationEvents>();
  87. // Compression Response
  88. services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
  89. services.AddResponseCompression(options => {
  90. options.Providers.Add<GzipCompressionProvider>();
  91. });
  92. services.AddHttpsRedirection(options =>
  93. {
  94. options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
  95. });
  96. // Sessions
  97. services.AddResponseCaching();
  98. services.AddMemoryCache();
  99. services.AddSession();
  100. // Set the anti-forgery cookie name
  101. services.AddAntiforgery(options =>
  102. {
  103. options.Cookie.Name = "TeknikAntiForgery";
  104. options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
  105. options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
  106. });
  107. // Core MVC
  108. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  109. //services.AddIdentityServer()
  110. // .AddResourceOwnerValidator<ResourceOwnerPasswordValidator>();
  111. }
  112. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  113. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, TeknikEntities dbContext, Config config)
  114. {
  115. // Create and Migrate the database
  116. dbContext.Database.Migrate();
  117. // Initiate Logging
  118. loggerFactory.AddLogger(config);
  119. // Setup the HttpContext
  120. app.UseHttpContextSetup();
  121. // HttpContext Session
  122. app.UseSession(new SessionOptions()
  123. {
  124. IdleTimeout = TimeSpan.FromMinutes(30),
  125. Cookie = new CookieBuilder()
  126. {
  127. Domain = null,
  128. Name = "TeknikSession",
  129. SecurePolicy = CookieSecurePolicy.Always,
  130. SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict
  131. }
  132. });
  133. // Use Exception Handling
  134. app.UseErrorHandler(config);
  135. if (env.IsDevelopment())
  136. {
  137. app.UseBrowserLink();
  138. //app.UseDeveloperExceptionPage();
  139. app.UseDatabaseErrorPage();
  140. }
  141. // Performance Monitor the entire request
  142. app.UsePerformanceMonitor();
  143. // Custom Middleware
  144. app.UseBlacklist();
  145. app.UseCORS();
  146. app.UseCSP();
  147. app.UseSecurityHeaders();
  148. // Cache Responses
  149. app.UseResponseCaching();
  150. // Force a HTTPS redirection (301)
  151. app.UseHttpsRedirection();
  152. // Setup static files anc cache them client side
  153. app.UseStaticFiles(new StaticFileOptions
  154. {
  155. OnPrepareResponse = ctx =>
  156. {
  157. ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=" + 31536000;
  158. }
  159. });
  160. // Enable Cookie Policy
  161. app.UseCookiePolicy();
  162. // Authorize all the things!
  163. app.UseAuthentication();
  164. // And finally, let's use MVC
  165. app.UseMvc(routes =>
  166. {
  167. routes.BuildRoutes(config);
  168. });
  169. }
  170. }
  171. }