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

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