Startup.cs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IdentityModel.Tokens.Jwt;
  4. using System.Linq;
  5. using System.Security.Claims;
  6. using System.Text.Json;
  7. using System.Threading.Tasks;
  8. using Microsoft.AspNetCore.Authentication.JwtBearer;
  9. using Microsoft.AspNetCore.Builder;
  10. using Microsoft.AspNetCore.Hosting;
  11. using Microsoft.AspNetCore.Http;
  12. using Microsoft.Extensions.Configuration;
  13. using Microsoft.Extensions.DependencyInjection;
  14. using Microsoft.Extensions.Hosting;
  15. using Microsoft.Extensions.Primitives;
  16. using Microsoft.IdentityModel.Tokens;
  17. using TEAMModelOS.SDK.Context.Configuration;
  18. using TEAMModelOS.SDK.DI;
  19. using Microsoft.Extensions.Diagnostics.HealthChecks;
  20. namespace TEAMModelGrpc
  21. {
  22. public class Startup
  23. {
  24. private IConfiguration _conf;
  25. public Startup(IConfiguration conf)
  26. {
  27. _conf = conf;
  28. }
  29. // This method gets called by the runtime. Use this method to add services to the container.
  30. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
  31. public void ConfigureServices(IServiceCollection services)
  32. {
  33. services.AddGrpc();
  34. //添加Grpc扩展
  35. // services.AddGrpcExtensions(_conf);
  36. //Grpc健康检查
  37. services.AddGrpcHealthChecks()
  38. .AddAsyncCheck("", () =>
  39. {
  40. var r = new Random();
  41. var result = r.Next() % 5 == 0
  42. ? HealthCheckResult.Unhealthy()
  43. : HealthCheckResult.Healthy();
  44. return Task.FromResult(result);
  45. }, Array.Empty<string>());
  46. services.AddAuthorization(options =>
  47. {
  48. options.AddPolicy(JwtBearerDefaults.AuthenticationScheme, policy =>
  49. {
  50. policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
  51. policy.RequireClaim(ClaimTypes.Name);
  52. });
  53. });
  54. services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
  55. .AddJwtBearer(options =>
  56. {
  57. options.TokenValidationParameters =
  58. new TokenValidationParameters
  59. {
  60. ValidateAudience = false,
  61. ValidateIssuer = false,
  62. ValidateActor = false,
  63. ValidateLifetime = true,
  64. IssuerSigningKey = SecurityKey
  65. };
  66. });
  67. // Table配置
  68. //services.AddScoped<IAzureTableDBRepository, AzureTableDBRepository>();
  69. //使用Blob配置
  70. //services.AddAzureBlobStorage().AddConnection(_conf.GetSection("Azure:Blob").Get<AzureBlobOptions>());
  71. //使用CosmosDB
  72. //services.AddAzureCosmosDBV3().AddCosmosDBV3Connection(_conf.GetSection("Azure:CosmosDB").Get<AzureCosmosDBOptions>())
  73. // .AddCosmosSerializer(new SystemTextJsonCosmosSerializer(new JsonSerializerOptions() { IgnoreNullValues = true }));
  74. //注入CSRedis
  75. // var csredis = new CSRedis.CSRedisClient(_conf.GetSection("Azure:Redis:ConnectionString").Get<string>());
  76. // RedisHelper.Initialization(csredis);
  77. //全局扫描基于IBusinessService接口的实现类
  78. //services.Scan(scan => scan.FromApplicationDependencies()
  79. // .AddClasses(classes => classes.AssignableTo<IBusinessService>())
  80. // .AsImplementedInterfaces()
  81. // .WithScopedLifetime());
  82. }
  83. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  84. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  85. {
  86. if (env.IsDevelopment())
  87. {
  88. app.UseDeveloperExceptionPage();
  89. }
  90. app.UseRouting();
  91. //注册 ASP.NET Core 身份验证中间件的顺序很重要。
  92. //始终在 UseRouting 之后和 UseEndpoints 之前调用 UseAuthentication 和 UseAuthorization。
  93. app.UseAuthentication();
  94. app.UseAuthorization();
  95. app.UseEndpoints(endpoints =>
  96. {
  97. // endpoints.MapGrpcService<HomeWorkService>();
  98. endpoints.MapGrpcHealthChecksService();
  99. endpoints.MapGet("/generateJwtToken", context =>
  100. {
  101. return context.Response.WriteAsync(GenerateJwtToken(context.Request.Query["name"]));
  102. });
  103. endpoints.MapGet("/", async context =>
  104. {
  105. await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
  106. });
  107. });
  108. //CodeFirst的Grpc(会自动扫描TStartup所在程序集下的IGrpcSerivce)
  109. //app.UseGrpcExtensions<TEAMModelGrpc.Services.HomeWorkService>(options =>
  110. //{
  111. // //CodeFirst配制
  112. // options.GlobalPackage = "TMDGrpc";
  113. // options.ProtoNameSpace = "TMDGrpc";
  114. //})
  115. //CodeFirst生成proto
  116. //.UseProtoGenerate("protos", false);
  117. }
  118. private string GenerateJwtToken(string name)
  119. {
  120. if (string.IsNullOrEmpty(name))
  121. {
  122. throw new InvalidOperationException("Name is not specified.");
  123. }
  124. var claims = new[] { new Claim(ClaimTypes.Name, name) };
  125. var credentials = new SigningCredentials(SecurityKey, SecurityAlgorithms.HmacSha256);
  126. var token = new JwtSecurityToken("ExampleServer", "ExampleClients", claims, expires: DateTime.Now.AddSeconds(60), signingCredentials: credentials);
  127. return JwtTokenHandler.WriteToken(token);
  128. }
  129. private readonly JwtSecurityTokenHandler JwtTokenHandler = new JwtSecurityTokenHandler();
  130. private readonly SymmetricSecurityKey SecurityKey = new SymmetricSecurityKey(Guid.NewGuid().ToByteArray());
  131. }
  132. }