Startup.cs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  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. namespace TEAMModelAPI
  19. {
  20. public class Startup
  21. {
  22. readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
  23. public Startup(IConfiguration configuration)
  24. {
  25. Configuration = configuration;
  26. }
  27. public IConfiguration Configuration { get; }
  28. // This method gets called by the runtime. Use this method to add services to the container.
  29. public void ConfigureServices(IServiceCollection services)
  30. {
  31. JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
  32. services.AddAuthentication(options => options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
  33. .AddJwtBearer(options => //AzureADJwtBearer
  34. {
  35. //options.SaveToken = true; //驗證令牌由服務器生成才有效,不適用於服務重啟或分布式架構
  36. options.Authority = Configuration["Option:Authority"];
  37. options.Audience = Configuration["Option:Audience"];
  38. options.RequireHttpsMetadata = true;
  39. options.TokenValidationParameters = new TokenValidationParameters
  40. {
  41. RoleClaimType = "roles",
  42. ValidAudiences = new string[] { Configuration["Option:Audience"], $"api://{Configuration["Option:Audience"]}" }
  43. };
  44. options.Events = new JwtBearerEvents();
  45. //下列事件有需要紀錄則打開
  46. //options.Events.OnMessageReceived = async context => { await Task.FromResult(0); };
  47. //options.Events.OnForbidden = async context => { await Task.FromResult(0); };
  48. //options.Events.OnChallenge = async context => { await Task.FromResult(0); };
  49. //options.Events.OnAuthenticationFailed = async context => { await Task.FromResult(0); };
  50. options.Events.OnTokenValidated = async context =>
  51. {
  52. if (!context.Principal.Claims.Any(x => x.Type == "http://schemas.microsoft.com/identity/claims/scope") //ClaimConstants.Scope
  53. && !context.Principal.Claims.Any(y => y.Type == "roles")) //ClaimConstants.Roles //http://schemas.microsoft.com/ws/2008/06/identity/claims/role
  54. {
  55. //TODO 需處理額外授權非角色及範圍的訪問異常紀錄
  56. throw new UnauthorizedAccessException("Neither scope or roles claim was found in the bearer token.");
  57. }
  58. await Task.FromResult(0);
  59. };
  60. });
  61. //設定跨域請求
  62. services.AddCors(options =>
  63. {
  64. options.AddPolicy(MyAllowSpecificOrigins,
  65. builder =>
  66. {
  67. builder.WithOrigins("http://teammodelos-test.chinacloudsites.cn",
  68. "https://www.teammodel.cn", "https://localhost:5001",
  69. "http://localhost:5000", "http://localhost:64524",
  70. "https://localhost:44341", "https://localhost:8888", "http://localhost:8888")
  71. .AllowAnyHeader()
  72. .AllowAnyMethod();
  73. });
  74. });
  75. services.AddControllers().AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = false; });
  76. services.AddAzureStorage(Configuration.GetValue<string>("Azure:Storage:ConnectionString"));
  77. services.AddAzureRedis(Configuration.GetValue<string>("Azure:Redis:ConnectionString"));
  78. services.AddAzureCosmos(Configuration.GetValue<string>("Azure:Cosmos:ConnectionString"));
  79. services.AddMemoryCache();
  80. services.AddSnowflakeId(Convert.ToInt64(Configuration.GetValue<string>("Option:LocationNum")), 1);
  81. services.AddHttpClient();
  82. services.AddHttpClient<DingDing>();
  83. services.AddAzureServiceBus(Configuration.GetValue<string>("Azure:ServiceBus:ConnectionString"));
  84. //HttpContextAccessor,并用来访问HttpContext。(提供組件或非控制器服務存取HttpContext)
  85. services.AddHttpContextAccessor();
  86. services.Configure<Option>(options => Configuration.GetSection("Option").Bind(options));
  87. }
  88. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  89. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  90. {
  91. if (env.IsDevelopment())
  92. {
  93. app.UseDeveloperExceptionPage();
  94. }
  95. app.UseHttpsRedirection();
  96. app.UseRouting();
  97. app.UseCors(MyAllowSpecificOrigins); //使用跨域設定
  98. app.UseAuthentication();
  99. app.UseAuthorization();
  100. app.UseEndpoints(endpoints =>
  101. {
  102. endpoints.MapControllers();
  103. });
  104. }
  105. }
  106. }