Startup.cs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Linq;
  5. using System.Reflection;
  6. using System.Text;
  7. using System.Text.Json;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. using Microsoft.AspNetCore.Authentication.JwtBearer;
  11. using Microsoft.AspNetCore.Builder;
  12. using Microsoft.AspNetCore.Hosting;
  13. using Microsoft.AspNetCore.Http;
  14. using Microsoft.AspNetCore.Http.Features;
  15. using Microsoft.AspNetCore.Mvc;
  16. using Microsoft.AspNetCore.SpaServices;
  17. using Microsoft.Azure.ServiceBus;
  18. using Microsoft.Extensions.Configuration;
  19. using Microsoft.Extensions.DependencyInjection;
  20. using Microsoft.Extensions.Hosting;
  21. using Microsoft.IdentityModel.Tokens;
  22. using Scrutor;
  23. using TEAMModelOS.Models;
  24. using TEAMModelOS.SDK;
  25. using TEAMModelOS.SDK.Context.Attributes.Azure;
  26. using TEAMModelOS.SDK.Context.Configuration;
  27. using TEAMModelOS.SDK.Context.Filter;
  28. using TEAMModelOS.SDK.DI;
  29. using TEAMModelOS.SDK.Module.AzureServiceBus;
  30. using TEAMModelOS.Service.Services.Learn.Implements;
  31. using TEAMModelOS.Service.Services.Learn.Interfaces;
  32. using VueCliMiddleware;
  33. namespace TEAMModelOS
  34. {
  35. public class Startup
  36. {
  37. //private IServiceCollection _services;
  38. public Startup(IConfiguration configuration, IWebHostEnvironment env)
  39. {
  40. Configuration = configuration;
  41. BaseConfigModel.SetBaseConfig(Configuration, env.ContentRootPath, env.WebRootPath);
  42. }
  43. public IConfiguration Configuration { get; }
  44. // This method gets called by the runtime. Use this method to add services to the container.
  45. public void ConfigureServices(IServiceCollection services)
  46. {
  47. // true,默認情況下,聲明映射將以舊格式映射聲明名稱,以適應較早的SAML應用程序,RoleClaimType = 'http://schemas.microsoft.com/ws/2008/06/identity/claims/role'
  48. // false,RoleClaimType = 'roles'
  49. JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
  50. services.AddAuthentication(options => options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
  51. .AddJwtBearer(options => //AzureADJwtBearer
  52. {
  53. //options.SaveToken = true; //驗證令牌由服務器生成才有效,不適用於服務重啟或分布式架構
  54. options.Authority = Configuration["Option:Authority"];
  55. options.Audience = Configuration["Option:Audience"];
  56. options.RequireHttpsMetadata = true;
  57. options.TokenValidationParameters = new TokenValidationParameters
  58. {
  59. RoleClaimType = "roles",
  60. ValidAudiences = new string[] { Configuration["Option:Audience"], $"api://{Configuration["Option:Audience"]}" }
  61. };
  62. options.Events = new JwtBearerEvents();
  63. //下列事件有需要紀錄則打開
  64. //options.Events.OnMessageReceived = async context => { await Task.FromResult(0); };
  65. //options.Events.OnForbidden = async context => { await Task.FromResult(0); };
  66. //options.Events.OnChallenge = async context => { await Task.FromResult(0); };
  67. //options.Events.OnAuthenticationFailed = async context => { await Task.FromResult(0); };
  68. options.Events.OnTokenValidated = async context =>
  69. {
  70. if (!context.Principal.Claims.Any(x => x.Type == "http://schemas.microsoft.com/identity/claims/scope") //ClaimConstants.Scope
  71. && !context.Principal.Claims.Any(y => y.Type == "roles")) //ClaimConstants.Roles //http://schemas.microsoft.com/ws/2008/06/identity/claims/role
  72. {
  73. //TODO 需處理額外授權非角色及範圍的訪問異常紀錄
  74. throw new UnauthorizedAccessException("Neither scope or roles claim was found in the bearer token.");
  75. }
  76. await Task.FromResult(0);
  77. };
  78. });
  79. services.AddAzureStorage(Configuration.GetValue<string>("Azure:Starage:ConnectionString"));
  80. services.AddAzureRedis( Configuration.GetValue<string>("Azure:Redis:ConnectionString"));
  81. services.AddAzureCosmos(Configuration.GetValue<string>("Azure:Cosmos:ConnectionString"));
  82. services.AddSnowflakeId(Convert.ToInt64(Configuration.GetValue<string>("Option:LocationNum")), 1);
  83. services.AddHttpClient();
  84. services.AddHttpClient<DingDing>();
  85. services.AddMemoryCache();
  86. services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = false; });
  87. services.Configure<Option>(options => Configuration.GetSection("Option").Bind(options));
  88. //Table配置
  89. // services.AddScoped<IAzureTableDBRepository, AzureTableDBRepository>();
  90. //使用Blob配置
  91. //services.AddAzureBlobStorage().AddConnection(Configuration.GetSection("Azure:Blob").Get<AzureBlobOptions>());
  92. //使用AzureServiceBus
  93. services.AddServiceBus().AddServiceBusOptions(Configuration.GetSection("Azure:ServiceBus").Get<AzureServiceBusOptions>());
  94. services.AddSingleton<IServiceBusService, ServiceBusService>();
  95. //HttpContextAccessor,并用来访问HttpContext。
  96. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
  97. //services.AddSingleton<IServiceBusReviceService, ServiceBusReviceService>();
  98. //注入CSRedis
  99. var csredis = new CSRedis.CSRedisClient(Configuration.GetSection("Azure:Redis:ConnectionString").Get<string>());
  100. RedisHelper.Initialization(csredis);
  101. }
  102. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  103. public void Configure(IApplicationBuilder app, IWebHostEnvironment env )
  104. {
  105. if (env.IsDevelopment())
  106. {
  107. app.UseDeveloperExceptionPage();
  108. }
  109. //app.UseMiddleware<HttpGlobalExceptionInvoke>();
  110. //以下需要按照順序載入中間件 如果应用调用 UseStaticFiles,请将 UseStaticFiles 置于 UseRouting之前。
  111. app.UseStaticFiles();
  112. //app.UseSpaStaticFiles(); //使用中間件不開
  113. app.UseRouting();
  114. //app.UseCors(MyAllowSpecificOrigins); //使用跨域設定
  115. //app.UseHttpsRedirection(); //開發中暫時關掉
  116. //如果应用使用身份验证/授权功能(如 AuthorizePage 或 [Authorize]),请将对 UseAuthentication 和 UseAuthorization的
  117. //调用放在之后、UseRouting 和 UseCors,但在 UseEndpoints之前
  118. app.UseAuthentication();
  119. app.UseAuthorization();
  120. // app.UseJsonRpc();
  121. app.UseEndpoints(endpoints =>
  122. {
  123. endpoints.MapControllers();
  124. #if DEBUG
  125. endpoints.MapToVueCliProxy(
  126. "{*path}",
  127. new SpaOptions { SourcePath = "ClientApp", },
  128. npmScript: (System.Diagnostics.Debugger.IsAttached) ? "serve" : null
  129. );
  130. #else
  131. endpoints.MapFallbackToFile("index.html");
  132. #endif
  133. //endpoints.MapGet("/", async context =>
  134. //{
  135. // await context.Response.WriteAsync("Hello World!");
  136. //});
  137. });
  138. }
  139. }
  140. }