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

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