Program.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. using Hangfire;
  2. using Hangfire.Redis.StackExchange;
  3. using Microsoft.AspNetCore.Authentication.JwtBearer;
  4. using Microsoft.Extensions.DependencyInjection.Extensions;
  5. using Microsoft.IdentityModel.Tokens;
  6. using System.IdentityModel.Tokens.Jwt;
  7. using TEAMModelOS.SDK.DI;
  8. using TEAMModelOS.SDK;
  9. using HTEX.Complex.Services;
  10. using HTEX.Complex.Services.MQTT;
  11. using MathNet.Numerics;
  12. using MQTTnet.AspNetCore;
  13. using MQTTnet.Server;
  14. using Microsoft.Extensions.Options;
  15. using System.Threading;
  16. using Microsoft.Extensions.Logging;
  17. using System.Text.Json;
  18. using Microsoft.Extensions.Hosting;
  19. using MQTTnet.AspNetCore.Routing;
  20. using Microsoft.AspNetCore.Builder;
  21. namespace HTEX.Complex
  22. {
  23. public class Program
  24. {
  25. public static void Main(string[] args)
  26. {
  27. var builder = WebApplication.CreateBuilder(args);
  28. //builder.WebHost.ConfigureKestrel(options =>
  29. //{
  30. // //options.ListenAnyIP(4001, options => {
  31. // // // options.UseHttps("Crt/iteden.pfx", "iteden");
  32. // //});
  33. // options.ListenAnyIP(1883, options => { options.UseMqtt();/*options.UseHttps("Crt/iteden.pfx", "iteden");*/ });
  34. // options.ListenAnyIP(1884, options => { options.UseMqtt();/* options.UseHttps("Configs/Crt/iteden.pfx", "iteden"); */}); // Default HTTP pipeline
  35. //});
  36. //builder.WebHost.ConfigureKestrel(options =>
  37. //{
  38. // //options.ListenAnyIP(4001, options => {
  39. // // // options.UseHttps("Crt/iteden.pfx", "iteden");
  40. // //});
  41. // options.ListenAnyIP(1883, options => { options.UseMqtt();/*options.UseHttps("Crt/iteden.pfx", "iteden");*/ });
  42. // options.ListenAnyIP(1884, options => { options.UseMqtt();/* options.UseHttps("Configs/Crt/iteden.pfx", "iteden"); */}); // Default HTTP pipeline
  43. //});
  44. // Add services to the container.
  45. JwtSecurityTokenHandler.DefaultMapInboundClaims = false;
  46. builder.Services.AddAuthentication(options => options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme)
  47. .AddJwtBearer(options => //AzureADJwtBearer
  48. {
  49. //options.SaveToken = true; //驗證令牌由服務器生成才有效,不適用於服務重啟或分布式架構
  50. options.Authority ="https://login.chinacloudapi.cn/4807e9cf-87b8-4174-aa5b-e76497d7392b/v2.0";// builder.Configuration["Option:Authority"];
  51. options.Audience = "72643704-b2e7-4b26-b881-bd5865e7a7a5";//builder.Configuration["Option:Audience"];
  52. options.RequireHttpsMetadata = true;
  53. options.TokenValidationParameters = new TokenValidationParameters
  54. {
  55. RoleClaimType = "roles",
  56. //ValidAudiences = new string[] { builder.Configuration["Option:Audience"], $"api://{builder.Configuration["Option:Audience"]}" }
  57. ValidAudiences = new string[] { "72643704-b2e7-4b26-b881-bd5865e7a7a5", $"api://72643704-b2e7-4b26-b881-bd5865e7a7a5" }
  58. };
  59. options.Events = new JwtBearerEvents();
  60. //下列事件有需要紀錄則打開
  61. //options.Events.OnMessageReceived = async context => { await Task.FromResult(0); };
  62. //options.Events.OnForbidden = async context => { await Task.FromResult(0); };
  63. //options.Events.OnChallenge = async context => { await Task.FromResult(0); };
  64. //options.Events.OnAuthenticationFailed = async context => { await Task.FromResult(0); };
  65. options.Events.OnTokenValidated = async context =>
  66. {
  67. if (!context.Principal.Claims.Any(x => x.Type.Equals("http://schemas.microsoft.com/identity/claims/scope")) //ClaimConstants.Scope
  68. && !context.Principal.Claims.Any(y => y.Type.Equals("roles"))) //ClaimConstants.Roles //http://schemas.microsoft.com/ws/2008/06/identity/claims/role
  69. {
  70. //TODO 需處理額外授權非角色及範圍的訪問異常紀錄
  71. throw new UnauthorizedAccessException("Neither scope or roles claim was found in the bearer token.");
  72. }
  73. await Task.FromResult(0);
  74. };
  75. });
  76. builder.Services.AddControllers();
  77. // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
  78. builder.Services.AddEndpointsApiExplorer();
  79. //builder.Services.AddSwaggerGen();
  80. builder.Services.AddHttpClient();
  81. string? StorageConnectionString = builder.Configuration.GetValue<string>("Azure:Storage:ConnectionString");
  82. string? RedisConnectionString = builder.Configuration.GetValue<string>("Azure:Redis:ConnectionString");
  83. //Storage
  84. builder.Services.AddAzureStorage(StorageConnectionString, "Default");
  85. //Redis
  86. builder.Services.AddAzureRedis(RedisConnectionString, "Default");
  87. string? StorageConnectionStringTest = builder.Configuration.GetValue<string>("Azure:Storage:ConnectionString-Test");
  88. //Storage
  89. builder.Services.AddAzureStorage(StorageConnectionString, "Test");
  90. builder.Services.AddSignalR();
  91. builder.Services.AddHttpContextAccessor();
  92. builder.Services.AddHttpClient<DingDing>();
  93. string path = $"{builder.Environment.ContentRootPath}/JsonFiles";
  94. builder.Services.TryAddSingleton(new Region2LongitudeLatitudeTranslator(path));
  95. builder.Services.AddIPSearcher(path);
  96. builder.Services.AddCors(options =>
  97. {
  98. options.AddDefaultPolicy(
  99. builder =>
  100. {
  101. builder.AllowAnyOrigin()
  102. .AllowAnyHeader()
  103. .AllowAnyMethod();
  104. });
  105. });
  106. builder.Services.AddControllersWithViews();
  107. //MQTT 服务端API 发送消息到MQTT客户端 https://www.cnblogs.com/weskynet/p/16441219.html
  108. #region MQTT配置
  109. builder.Services.AddSingleton<MQTTEvents>();
  110. builder.Services.AddSingleton(new JsonSerializerOptions(JsonSerializerDefaults.Web));
  111. builder.Services.AddHostedMqttServerWithServices(x =>
  112. {
  113. x.WithDefaultEndpoint()
  114. .WithConnectionBacklog(1000)
  115. .WithPersistentSessions(true).WithKeepAlive()
  116. .WithDefaultCommunicationTimeout(TimeSpan.FromMilliseconds(30));
  117. }).AddMqttConnectionHandler().AddConnections().AddMqttControllers();
  118. #endregion
  119. var app = builder.Build();
  120. // Configure the HTTP request pipeline.
  121. if (!app.Environment.IsDevelopment())
  122. {
  123. app.UseExceptionHandler("/Home/Error");
  124. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  125. app.UseHsts();
  126. }
  127. app.UseRouting();
  128. app.UseCors(); //使用跨域設定
  129. app.UseAuthentication();
  130. app.UseAuthorization();
  131. app.MapControllers();
  132. app.MapHub<SignalRScreenServerHub>("/signalr/screen").RequireCors("any");
  133. app.MapConnectionHandler<MqttConnectionHandler>("/mqtt", opts => opts.WebSockets.SubProtocolSelector = protocolList => protocolList.FirstOrDefault() ?? string.Empty);
  134. var events = app.Services.GetRequiredService<MQTTEvents>();
  135. app.UseMqttServer(server =>
  136. {
  137. server.WithAttributeRouting(app.Services, allowUnmatchedRoutes: false);
  138. server.ClientSubscribedTopicAsync+=events._mqttServer_ClientSubscribedTopicAsync;// 客户端订阅主题事件
  139. server.StoppedAsync+=events._mqttServer_StoppedAsync;// 关闭后事件
  140. server.ValidatingConnectionAsync+=events._mqttServer_ValidatingConnectionAsync; // 用户名和密码验证有关
  141. server.InterceptingPublishAsync+=events._mqttServer_InterceptingPublishAsync;// 消息接收事件
  142. server.StartedAsync+=events._mqttServer_StartedAsync;// 启动后事件
  143. server.ClientUnsubscribedTopicAsync+=events._mqttServer_ClientUnsubscribedTopicAsync;// 客户端取消订阅事件
  144. server.ApplicationMessageNotConsumedAsync+=events._mqttServer_ApplicationMessageNotConsumedAsync; // 消息接收事件,应用程序消息未使用
  145. server.ClientDisconnectedAsync+=events._mqttServer_ClientDisconnectedAsync;// 客户端关闭事件
  146. server.ClientConnectedAsync+=events._mqttServer_ClientConnectedAsync;//客户端连接事件
  147. //server.InterceptingClientEnqueueAsync += events._mqttServer_InterceptingClientEnqueueAsync;//拦截客户端排队
  148. //server.ClientAcknowledgedPublishPacketAsync += events._mqttServer_ClientAcknowledgedPublishPacketAsync;//已确认发布数据包
  149. });
  150. app.Run();
  151. }
  152. }
  153. }