Startup.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Security.Claims;
  5. using System.Text;
  6. using System.Text.Encodings.Web;
  7. using System.Text.Unicode;
  8. using HaBookCms.AzureCosmos.ServiceExtension;
  9. using HaBookCms.AzureStorage.ServiceExtension;
  10. using HaBookCms.Common.LogHelper;
  11. using HaBookCms.ContextConfig.Attributes;
  12. using HaBookCms.ContextConfig.Exceptions;
  13. using HaBookCms.Jwt.Filter;
  14. using HaBookCms.Jwt.Model;
  15. using HaBookCms.RedisStorage.Cache;
  16. using HaBookCms.ServiceOptions.Options;
  17. using log4net;
  18. using log4net.Config;
  19. using log4net.Repository;
  20. using Microsoft.AspNetCore.Authentication.JwtBearer;
  21. using Microsoft.AspNetCore.Builder;
  22. using Microsoft.AspNetCore.Hosting;
  23. using Microsoft.AspNetCore.Http;
  24. using Microsoft.AspNetCore.HttpOverrides;
  25. using Microsoft.AspNetCore.Mvc;
  26. using Microsoft.AspNetCore.SpaServices.Webpack;
  27. using Microsoft.Extensions.Configuration;
  28. using Microsoft.Extensions.DependencyInjection;
  29. using Microsoft.IdentityModel.Tokens;
  30. namespace HaBookCms.Contest
  31. {
  32. public class Startup
  33. {
  34. /// <summary>
  35. /// log4net 仓储库
  36. /// </summary>
  37. public static ILoggerRepository repository { get; set; }
  38. public Startup(IConfiguration configuration, IHostingEnvironment env)
  39. {
  40. Configuration = configuration;
  41. var builder = new ConfigurationBuilder()
  42. .SetBasePath(env.ContentRootPath)
  43. .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
  44. this.Configuration = builder.Build();
  45. //log4net
  46. repository = LogManager.CreateRepository("HaBookCms");
  47. //指定配置文件
  48. XmlConfigurator.Configure(repository, new FileInfo("Log4net.config"));
  49. BaseConfigModel.SetBaseConfig(Configuration, env.ContentRootPath, env.WebRootPath);
  50. }
  51. public IConfiguration Configuration { get; }
  52. // This method gets called by the runtime. Use this method to add services to the container.
  53. public void ConfigureServices(IServiceCollection services)
  54. {//Configuration["AppSettings:Azure:TableStorageConnection"]
  55. services.AddAzureTableStorage().AddAzureBlobStorage().AddConnection(new AzureStorageOptions
  56. {
  57. ConnectionString = Configuration["AppSettings:Azure:StorageConnection"]
  58. });
  59. services.Configure<CookiePolicyOptions>(options =>
  60. {
  61. // This lambda determines whether user consent for non-essential cookies is needed for a given request.
  62. options.CheckConsentNeeded = context => true;
  63. options.MinimumSameSitePolicy = SameSiteMode.None;
  64. });
  65. services.AddAzureCosmosDB().AddCosmosDBConnection(new AzureCosmosDBOptions() {
  66. ConnectionString = Configuration["AppSettings:Azure:CosmosDBConnection:AccountEndpoint"],
  67. ConnectionKey= Configuration["AppSettings:Azure:CosmosDBConnection:AccountKey"],
  68. Database = Configuration["AppSettings:Azure:CosmosDBConnection:Database"],
  69. });
  70. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  71. //services.AddMvc().AddMvcOptions(
  72. // option =>
  73. // {
  74. // option.OutputFormatters.Clear();
  75. // option.OutputFormatters.Add(new MessagePackOutputFormatter(ContractlessStandardResolver.Instance));
  76. // option.InputFormatters.Clear();
  77. // option.InputFormatters.Add(new MessagePackInputFormatter(ContractlessStandardResolver.Instance));
  78. // });
  79. //解决视图输出内容中文编码问题
  80. services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));
  81. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  82. #region 认证
  83. JwtAuthConfigModel jwtConfig = new JwtAuthConfigModel();
  84. // services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
  85. //.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
  86. // {
  87. // o.LoginPath = new PathString("/api/Users/checkLogin");
  88. // })
  89. services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  90. .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, o =>
  91. {
  92. o.TokenValidationParameters = new TokenValidationParameters
  93. {
  94. ValidIssuer = jwtConfig.Issuer,
  95. ValidAudience = jwtConfig.Audience,
  96. IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.JWTSecretKey)),
  97. /***********************************TokenValidationParameters的参数默认值***********************************/
  98. RequireSignedTokens = true,
  99. // SaveSigninToken = false,
  100. // ValidateActor = false,
  101. // 将下面两个参数设置为false,可以不验证Issuer和Audience,但是不建议这样做。
  102. ValidateAudience = true,
  103. ValidateIssuer = true,
  104. ValidateIssuerSigningKey = true,
  105. // 是否要求Token的Claims中必须包含 Expires
  106. RequireExpirationTime = true,
  107. // 允许的服务器时间偏移量
  108. // ClockSkew = TimeSpan.FromSeconds(300),
  109. ClockSkew = TimeSpan.Zero,
  110. // 是否验证Token有效期,使用当前时间与Token的Claims中的NotBefore和Expires对比
  111. ValidateLifetime = true
  112. };
  113. });
  114. #endregion
  115. var signingCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig.JWTSecretKey)), SecurityAlgorithms.HmacSha256);
  116. // 如果要数据库动态绑定,这里先留个空,后边处理器里动态赋值
  117. var permission = new List<Permission>();
  118. // 角色与接口的权限要求参数
  119. var permissionRequirement = new PermissionRequirement(
  120. "/api/denied",// 拒绝授权的跳转地址(目前无用)
  121. permission,
  122. ClaimTypes.Role,//基于角色的授权
  123. jwtConfig.Issuer,//发行人
  124. jwtConfig.Audience,//听众
  125. signingCredentials,//签名凭据
  126. expiration: TimeSpan.FromSeconds(60 * 2)//接口的过期时间
  127. );
  128. // services.AddSingleton<PermissionRequirement, PermissionRequirement>();
  129. #region 授权
  130. services.AddAuthorization(options =>
  131. {
  132. options.AddPolicy("RequireContestWeb", policy => policy.RequireRole("ContestWeb").Build());
  133. options.AddPolicy("RequireApp", policy => policy.RequireRole("App").Build());
  134. options.AddPolicy("RequireAdmin", policy => policy.RequireRole("Admin").Build());
  135. options.AddPolicy("RequireAdminOrApp", policy => policy.RequireRole("Admin,App").Build());
  136. // 自定义权限要求
  137. options.AddPolicy("Permission",
  138. policy => policy.Requirements.Add(permissionRequirement));
  139. });
  140. #endregion
  141. //log日志注入
  142. services.AddSingleton<ILoggerHelper, LogHelper>();
  143. #region 缓存 读取配置是否使用哪种缓存模式
  144. services.AddMemoryCache();
  145. if (Convert.ToBoolean(Configuration["Cache:IsUseRedis"]))
  146. {
  147. services.AddSingleton<ICacheService, RedisCacheService>();
  148. }
  149. else
  150. {
  151. services.AddSingleton<ICacheService, MemoryCacheService>();
  152. }
  153. #endregion
  154. #region 缓存 RedisCache
  155. //将Redis分布式缓存服务添加到服务中
  156. services.AddDistributedRedisCache(options =>
  157. {
  158. //用于连接Redis的配置
  159. options.Configuration = "localhost";// Configuration.GetConnectionString("RedisConnectionString");
  160. //Redis实例名RedisDistributedCache
  161. options.InstanceName = "RedisInstance";
  162. });
  163. #endregion
  164. #region CORS
  165. services.AddCors(c =>
  166. {
  167. c.AddPolicy("Any", policy =>
  168. {
  169. policy.AllowAnyOrigin()
  170. .AllowAnyMethod()
  171. .AllowAnyHeader()
  172. .AllowCredentials();
  173. });
  174. c.AddPolicy("Limit", policy =>
  175. {
  176. policy
  177. .WithOrigins("localhost:63969")
  178. .WithMethods("get", "post", "put", "delete")
  179. //.WithHeaders("Authorization");
  180. .AllowAnyHeader();
  181. });
  182. });
  183. #endregion
  184. #region 性能 压缩
  185. services.AddResponseCompression();
  186. #endregion
  187. //跨域//设置了允许所有来源
  188. services.AddCors(options =>
  189. options.AddPolicy("any",
  190. builder => builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));
  191. services.AddMvc(options =>
  192. {
  193. options.Filters.Add(new AllowCorsAttribute());
  194. });
  195. }
  196. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  197. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  198. {
  199. if (env.IsDevelopment())
  200. {
  201. app.UseDeveloperExceptionPage();
  202. //app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
  203. //{
  204. // HotModuleReplacement = true
  205. //});
  206. }
  207. else
  208. {
  209. app.UseExceptionHandler("/Home/Error");
  210. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  211. app.UseHsts();
  212. }
  213. #region 解决Ubuntu Nginx 代理不能获取IP问题
  214. app.UseForwardedHeaders(new ForwardedHeadersOptions
  215. {
  216. ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
  217. });
  218. #endregion
  219. app.UseHttpsRedirection();
  220. app.UseStaticFiles(new StaticFileOptions
  221. {
  222. ServeUnknownFileTypes = true
  223. //ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
  224. //{
  225. // { ".apk","application/vnd.android.package-archive"},
  226. // { ".nupkg","application/zip"}
  227. //}) //支持特殊文件下载处理
  228. });
  229. //自定义异常处理
  230. app.UseMiddleware<ExceptionFilter>();
  231. //认证
  232. app.UseAuthentication();
  233. //授权
  234. app.UseMiddleware<JwtAuthorizationFilter>();
  235. //性能压缩
  236. app.UseResponseCompression();
  237. app.UseCookiePolicy();
  238. app.UseMvc(routes =>
  239. {
  240. routes.MapRoute(
  241. name: "default",
  242. template: "{controller=Home}/{action=Index}/{id?}");
  243. });
  244. }
  245. }
  246. }