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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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 Microsoft.AspNetCore.Authentication.OpenIdConnect;
  27. using Teknik.Attributes;
  28. using Teknik.Filters;
  29. using Microsoft.Net.Http.Headers;
  30. using Teknik.Areas.Users.Models;
  31. using Microsoft.AspNetCore.Mvc.Infrastructure;
  32. using Microsoft.AspNetCore.Mvc.Routing;
  33. using Microsoft.AspNetCore.Http.Features;
  34. using Microsoft.IdentityModel.Tokens;
  35. using Microsoft.AspNetCore.Authentication;
  36. using IdentityModel;
  37. using Teknik.Security;
  38. using Microsoft.AspNetCore.Routing;
  39. using Microsoft.AspNetCore.Mvc.Internal;
  40. using Microsoft.AspNetCore.Authorization;
  41. using System.Text.Encodings.Web;
  42. namespace Teknik
  43. {
  44. public class Startup
  45. {
  46. public Startup(IConfiguration configuration, IHostingEnvironment env)
  47. {
  48. Configuration = configuration;
  49. Environment = env;
  50. }
  51. public IConfiguration Configuration { get; }
  52. public IHostingEnvironment Environment { get; }
  53. // This method gets called by the runtime. Use this method to add services to the container.
  54. public void ConfigureServices(IServiceCollection services)
  55. {
  56. string baseDir = Environment.ContentRootPath;
  57. string dataDir = Path.Combine(baseDir, "App_Data");
  58. AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
  59. // Setup IIS
  60. services.Configure<IISOptions>(options =>
  61. {
  62. options.ForwardClientCertificate = false;
  63. options.AutomaticAuthentication = false;
  64. });
  65. // HTTP Context
  66. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  67. // Create Configuration Singleton
  68. services.AddScoped<Config, Config>(opt => Config.Load(dataDir));
  69. // Build an intermediate service provider
  70. var sp = services.BuildServiceProvider();
  71. // Resolve the services from the service provider
  72. var config = sp.GetService<Config>();
  73. // Add Tracking Filter scopes
  74. //services.AddScoped<TrackDownload>();
  75. //services.AddScoped<TrackLink>();
  76. //services.AddScoped<TrackPageView>();
  77. // Create the Database Context
  78. services.AddDbContext<TeknikEntities>(options => options
  79. .UseLazyLoadingProxies()
  80. .UseSqlServer(Configuration.GetConnectionString("TeknikEntities")), ServiceLifetime.Transient);
  81. // Cookie Policies
  82. services.Configure<CookiePolicyOptions>(options =>
  83. {
  84. // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  85. options.CheckConsentNeeded = context => false;
  86. options.MinimumSameSitePolicy = Microsoft.AspNetCore.Http.SameSiteMode.None;
  87. });
  88. services.ConfigureApplicationCookie(options =>
  89. {
  90. options.Cookie.Name = "TeknikWeb";
  91. options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
  92. options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
  93. options.Cookie.Expiration = TimeSpan.FromDays(30);
  94. options.ExpireTimeSpan = TimeSpan.FromDays(30);
  95. });
  96. // Compression Response
  97. services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
  98. services.AddResponseCompression(options => {
  99. options.Providers.Add<GzipCompressionProvider>();
  100. });
  101. services.AddHttpsRedirection(options =>
  102. {
  103. options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
  104. });
  105. // Sessions
  106. services.AddResponseCaching();
  107. services.AddMemoryCache();
  108. services.AddSession();
  109. // Set the anti-forgery cookie name
  110. services.AddAntiforgery(options =>
  111. {
  112. options.Cookie.Name = "TeknikWebAntiForgery";
  113. options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
  114. options.Cookie.SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict;
  115. });
  116. // Core MVC
  117. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
  118. services.AddTransient<CookieEventHandler>();
  119. services.AddSingleton<LogoutSessionManager>();
  120. services.AddAuthentication(options =>
  121. {
  122. options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
  123. options.DefaultChallengeScheme = "oidc";
  124. })
  125. .AddIdentityServerAuthentication(options =>
  126. {
  127. options.Authority = config.UserConfig.IdentityServerConfig.Authority;
  128. options.RequireHttpsMetadata = true;
  129. options.ApiName = config.UserConfig.IdentityServerConfig.APIName;
  130. options.ApiSecret = config.UserConfig.IdentityServerConfig.APISecret;
  131. })
  132. .AddCookie(options =>
  133. {
  134. options.ExpireTimeSpan = TimeSpan.FromMinutes(60);
  135. options.Cookie.Name = "TeknikWebAuth";
  136. options.EventsType = typeof(CookieEventHandler);
  137. })
  138. .AddOpenIdConnect("oidc", options =>
  139. {
  140. options.SignInScheme = "Cookies";
  141. options.Authority = config.UserConfig.IdentityServerConfig.Authority;
  142. options.RequireHttpsMetadata = true;
  143. options.ClientId = config.UserConfig.IdentityServerConfig.ClientId;
  144. options.ClientSecret = config.UserConfig.IdentityServerConfig.ClientSecret;
  145. options.ResponseType = "code id_token";
  146. // Set the scopes to listen to
  147. options.Scope.Clear();
  148. options.Scope.Add("openid");
  149. options.Scope.Add("role");
  150. options.Scope.Add("account-info");
  151. options.Scope.Add("security-info");
  152. options.Scope.Add("teknik-api.read");
  153. options.Scope.Add("teknik-api.write");
  154. options.Scope.Add("offline_access");
  155. // Let's clear the claim actions and make our own mappings
  156. options.ClaimActions.Clear();
  157. options.ClaimActions.MapUniqueJsonKey("sub", "sub");
  158. options.ClaimActions.MapUniqueJsonKey("username", "username");
  159. options.ClaimActions.MapUniqueJsonKey("role", "role");
  160. options.ClaimActions.MapUniqueJsonKey("creation-date", "creation-date");
  161. options.ClaimActions.MapUniqueJsonKey("last-seen", "last-seen");
  162. options.ClaimActions.MapUniqueJsonKey("account-type", "account-type");
  163. options.ClaimActions.MapUniqueJsonKey("account-status", "account-status");
  164. options.ClaimActions.MapUniqueJsonKey("recovery-email", "recovery-email");
  165. options.ClaimActions.MapUniqueJsonKey("recovery-verified", "recovery-verified");
  166. options.ClaimActions.MapUniqueJsonKey("2fa-enabled", "2fa-enabled");
  167. options.ClaimActions.MapUniqueJsonKey("pgp-public-key", "pgp-public-key");
  168. options.GetClaimsFromUserInfoEndpoint = true;
  169. options.SaveTokens = true;
  170. options.TokenValidationParameters = new TokenValidationParameters
  171. {
  172. NameClaimType = "username",
  173. RoleClaimType = JwtClaimTypes.Role
  174. };
  175. options.Events.OnMessageReceived = ctx =>
  176. {
  177. if (!string.IsNullOrEmpty(ctx.ProtocolMessage.Error))
  178. {
  179. // We need to throw an actual error (not the one they do)
  180. switch (ctx.ProtocolMessage.Error)
  181. {
  182. case "access_denied":
  183. ctx.Response.StatusCode = 403;
  184. break;
  185. }
  186. }
  187. return Task.CompletedTask;
  188. };
  189. });
  190. services.AddAuthorization(options =>
  191. {
  192. options.AddPolicy("FullAPI", p =>
  193. {
  194. p.RequireScope("teknik-api.read");
  195. p.RequireScope("teknik-api.write");
  196. });
  197. options.AddPolicy("ReadOnlyAPI", p =>
  198. {
  199. p.RequireScope("teknik-api.read");
  200. });
  201. options.AddPolicy("WriteOnlyAPI", p =>
  202. {
  203. p.RequireScope("teknik-api.read");
  204. });
  205. options.AddPolicy("AnyAPI", p =>
  206. {
  207. p.RequireScope("teknik-api.read", "teknik-api.write");
  208. });
  209. });
  210. services.Configure<FormOptions>(x =>
  211. {
  212. x.ValueLengthLimit = int.MaxValue;
  213. x.MultipartBodyLengthLimit = long.MaxValue; // In case of multipart
  214. });
  215. }
  216. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  217. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, TeknikEntities dbContext, Config config)
  218. {
  219. // Create and Migrate the database
  220. dbContext.Database.Migrate();
  221. // Initiate Logging
  222. loggerFactory.AddLogger(config);
  223. // Setup the HttpContext
  224. app.UseHttpContextSetup();
  225. // HttpContext Session
  226. app.UseSession(new SessionOptions()
  227. {
  228. IdleTimeout = TimeSpan.FromMinutes(30),
  229. Cookie = new CookieBuilder()
  230. {
  231. Domain = null,
  232. Name = "TeknikWebSession",
  233. SecurePolicy = CookieSecurePolicy.SameAsRequest,
  234. SameSite = Microsoft.AspNetCore.Http.SameSiteMode.Strict
  235. }
  236. });
  237. // Use Exception Handling
  238. app.UseErrorHandler(config);
  239. if (env.IsDevelopment())
  240. {
  241. app.UseBrowserLink();
  242. //app.UseDeveloperExceptionPage();
  243. app.UseDatabaseErrorPage();
  244. }
  245. // Performance Monitor the entire request
  246. app.UsePerformanceMonitor();
  247. // Custom Middleware
  248. app.UseBlacklist();
  249. app.UseCORS();
  250. app.UseCSP();
  251. app.UseSecurityHeaders();
  252. // Cache Responses
  253. app.UseResponseCaching();
  254. // Force a HTTPS redirection (301)
  255. app.UseHttpsRedirection();
  256. // Setup static files anc cache them client side
  257. app.UseStaticFiles(new StaticFileOptions
  258. {
  259. OnPrepareResponse = ctx =>
  260. {
  261. ctx.Context.Response.Headers[HeaderNames.CacheControl] = "public,max-age=" + 31536000;
  262. }
  263. });
  264. // Enable Cookie Policy
  265. app.UseCookiePolicy();
  266. // Authorize all the things!
  267. app.UseAuthentication();
  268. // And finally, let's use MVC
  269. app.UseMvc(routes =>
  270. {
  271. routes.BuildRoutes(config);
  272. });
  273. }
  274. }
  275. }