Startup.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. using Microsoft.AspNetCore.Builder;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.AspNetCore.HttpsPolicy;
  4. using Microsoft.AspNetCore.Mvc;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.Hosting;
  8. using Microsoft.Extensions.Logging;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Threading.Tasks;
  13. using TEAMModelOS.Models;
  14. using TEAMModelOS.SDK.DI;
  15. using System.IdentityModel.Tokens.Jwt;
  16. using Microsoft.AspNetCore.Authentication.JwtBearer;
  17. using Microsoft.IdentityModel.Tokens;
  18. using TEAMModelOS.Filter;
  19. using TEAMModelOS.SDK.Helper.Common.ReflectorExtensions;
  20. using System.Reflection;
  21. using TEAMModelOS.SDK.Extension;
  22. using TEAMModelOS.SDK;
  23. using TEAMModelOS.SDK.Models;
  24. namespace TEAMModelAPI
  25. {
  26. public class Startup
  27. {
  28. readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
  29. public Startup(IConfiguration configuration)
  30. {
  31. Configuration = configuration;
  32. }
  33. public IConfiguration Configuration { get; }
  34. // This method gets called by the runtime. Use this method to add services to the container.
  35. public void ConfigureServices(IServiceCollection services)
  36. {
  37. JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
  38. services.AddAuthentication(options => options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
  39. .AddJwtBearer(options => //AzureADJwtBearer
  40. {
  41. //options.SaveToken = true; //驗證令牌由服務器生成才有效,不適用於服務重啟或分布式架構
  42. options.Authority = Configuration["Option:Authority"];
  43. options.Audience = Configuration["Option:Audience"];
  44. options.RequireHttpsMetadata = true;
  45. options.TokenValidationParameters = new TokenValidationParameters
  46. {
  47. RoleClaimType = "roles",
  48. ValidAudiences = new string[] { Configuration["Option:Audience"], $"api://{Configuration["Option:Audience"]}" }
  49. };
  50. options.Events = new JwtBearerEvents();
  51. //下列事件有需要紀錄則打開
  52. //options.Events.OnMessageReceived = async context => { await Task.FromResult(0); };
  53. //options.Events.OnForbidden = async context => { await Task.FromResult(0); };
  54. //options.Events.OnChallenge = async context => { await Task.FromResult(0); };
  55. //options.Events.OnAuthenticationFailed = async context => { await Task.FromResult(0); };
  56. options.Events.OnTokenValidated = async context =>
  57. {
  58. if (!context.Principal.Claims.Any(x => x.Type.Equals("http://schemas.microsoft.com/identity/claims/scope")) //ClaimConstants.Scope
  59. && !context.Principal.Claims.Any(y => y.Type .Equals("roles"))) //ClaimConstants.Roles //http://schemas.microsoft.com/ws/2008/06/identity/claims/role
  60. {
  61. //TODO 需處理額外授權非角色及範圍的訪問異常紀錄
  62. throw new UnauthorizedAccessException("Neither scope or roles claim was found in the bearer token.");
  63. }
  64. await Task.FromResult(0);
  65. };
  66. });
  67. //設定跨域請求
  68. services.AddCors(options =>
  69. {
  70. options.AddPolicy(MyAllowSpecificOrigins,
  71. builder =>
  72. {
  73. builder.WithOrigins("http://teammodelos-test.chinacloudsites.cn",
  74. "https://www.teammodel.cn", "https://localhost:5001",
  75. "http://localhost:5000", "http://localhost:64524",
  76. "https://localhost:44341", "https://localhost:8888", "http://localhost:8888")
  77. .AllowAnyHeader()
  78. .AllowAnyMethod();
  79. });
  80. });
  81. services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = false; });
  82. services.AddAzureStorage(Configuration.GetValue<string>("Azure:Storage:ConnectionString"));
  83. services.AddAzureRedis(Configuration.GetValue<string>("Azure:Redis:ConnectionString"));
  84. services.AddAzureCosmos(Configuration.GetValue<string>("Azure:Cosmos:ConnectionString"));
  85. services.AddAzureServiceBus(Configuration.GetValue<string>("Azure:ServiceBus:ConnectionString"));
  86. services.AddMemoryCache();
  87. services.AddSnowflakeId(Convert.ToInt64(Configuration.GetValue<string>("Option:LocationNum")), 1);
  88. services.AddHttpClient();
  89. services.AddHttpClient<DingDing>();
  90. services.AddCoreAPIHttpService(Configuration);
  91. //HttpContextAccessor,并用来访问HttpContext。(提供組件或非控制器服務存取HttpContext)
  92. services.AddHttpContextAccessor();
  93. services.Configure<Option>(options => Configuration.GetSection("Option").Bind(options));
  94. }
  95. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  96. public void Configure(IApplicationBuilder app, IWebHostEnvironment env,AzureStorageFactory azureStorage)
  97. {
  98. if (env.IsDevelopment())
  99. {
  100. app.UseDeveloperExceptionPage();
  101. }
  102. app.UseHttpsRedirection();
  103. app.UseRouting();
  104. app.UseCors(MyAllowSpecificOrigins); //使用跨域設定
  105. app.UseAuthentication();
  106. app.UseAuthorization();
  107. app.UseEndpoints(endpoints =>
  108. {
  109. endpoints.MapControllers();
  110. });
  111. #if DEBUG
  112. //在开发模式时,自检 [ApiToken(Auth = "1")] 有重复的接口 https://teammodelos.table.core.chinacloudapi.cn/IESOpenApi
  113. List<ApiTokenAttribute> auths = new List<ApiTokenAttribute>();
  114. List<Attribute> attributes = ReflectorExtensions.GetMethodCustomAttribute<ApiTokenAttribute>(new string[] { "TEAMModelAPI" });
  115. List<OpenApi> openApis = new List<OpenApi>();
  116. attributes.ForEach(x => {
  117. ApiTokenAttribute attribute = (ApiTokenAttribute)x;
  118. openApis.Add(new OpenApi {
  119. PartitionKey="IES5-API",
  120. RowKey= attribute.Auth,
  121. auth=int.Parse(attribute.Auth),
  122. // descr=attribute.Name,
  123. method="POST",
  124. name=attribute.Name,
  125. });
  126. auths.Add(attribute);
  127. });
  128. auths.GroupBy(x => x.Auth).ToList().ForEach(x => {
  129. if (x.Count() > 1)
  130. {
  131. throw new Exception($"接口Auth重复定义{x.ToList()}");
  132. }
  133. });
  134. var table = azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
  135. #endif
  136. }
  137. }
  138. }