Startup.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using IdentityServer4.AccessTokenValidation;
  2. using Microsoft.AspNetCore.Authentication;
  3. using Microsoft.AspNetCore.Builder;
  4. using Microsoft.AspNetCore.Hosting;
  5. using Microsoft.Extensions.Configuration;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Microsoft.Extensions.Hosting;
  8. using Microsoft.OpenApi.Models;
  9. using Ocelot.DependencyInjection;
  10. using Ocelot.Middleware;
  11. using QM.Gateway.Uses;
  12. using System;
  13. using System.Security.Cryptography;
  14. using System.Threading.Tasks;
  15. namespace QM.Gateway
  16. {
  17. public class Startup
  18. {
  19. public Startup(IConfiguration configuration)
  20. {
  21. Configuration = configuration;
  22. }
  23. public IConfiguration Configuration { get; }
  24. // This method gets called by the runtime. Use this method to add services to the container.
  25. public void ConfigureServices(IServiceCollection services)
  26. {
  27. services.AddControllers();
  28. services.AddSwaggerGen(c =>
  29. {
  30. c.SwaggerDoc("v1", new OpenApiInfo { Title = "QM.Gateway", Version = "v1" });
  31. });
  32. IdentityServerConfig identityServerConfig = new IdentityServerConfig();
  33. Configuration.Bind("IdentityServerConfig", identityServerConfig);
  34. var identityBuilder = services.AddAuthentication(identityServerConfig.IdentityScheme);
  35. if (identityServerConfig != null && identityServerConfig.ApiSecrets != null)
  36. {
  37. foreach (var resource in identityServerConfig.ApiSecrets)
  38. {
  39. identityBuilder.AddIdentityServerAuthentication(resource.Key, options =>
  40. {
  41. options.Authority = identityServerConfig.Url;
  42. options.RequireHttpsMetadata = identityServerConfig.UseHttps;
  43. options.ApiName = resource.Name;
  44. options.SupportedTokens = SupportedTokens.Both;
  45. options.ApiSecret = resource.Name;
  46. });
  47. }
  48. }
  49. // 注入Ocelot服务
  50. services.AddOcelot(Configuration);
  51. }
  52. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  53. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  54. {
  55. if (env.IsDevelopment())
  56. {
  57. app.UseDeveloperExceptionPage();
  58. app.UseSwagger();
  59. app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "QM.Gateway v1"));
  60. }
  61. app.UseHttpsRedirection();
  62. //使用Ocelot中间件
  63. //app.UseOcelot().Wait();
  64. app.UseOcelot((builder, config) =>
  65. {
  66. //自定义中间件
  67. app.UseBuildOcelotPipeline(config);
  68. }).Wait();
  69. app.UseRouting();
  70. app.UseAuthorization();
  71. app.UseEndpoints(endpoints =>
  72. {
  73. endpoints.MapControllers();
  74. });
  75. }
  76. }
  77. }