using IdentityServer4.AccessTokenValidation; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using Ocelot.DependencyInjection; using Ocelot.Middleware; using QM.Gateway.Uses; using System; using System.Security.Cryptography; using System.Threading.Tasks; namespace QM.Gateway { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "QM.Gateway", Version = "v1" }); }); IdentityServerConfig identityServerConfig = new IdentityServerConfig(); Configuration.Bind("IdentityServerConfig", identityServerConfig); var identityBuilder = services.AddAuthentication(identityServerConfig.IdentityScheme); if (identityServerConfig != null && identityServerConfig.ApiSecrets != null) { foreach (var resource in identityServerConfig.ApiSecrets) { identityBuilder.AddIdentityServerAuthentication(resource.Key, options => { options.Authority = identityServerConfig.Url; options.RequireHttpsMetadata = identityServerConfig.UseHttps; options.ApiName = resource.Name; options.SupportedTokens = SupportedTokens.Both; options.ApiSecret = resource.Name; }); } } // 注入Ocelot服务 services.AddOcelot(Configuration); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "QM.Gateway v1")); } app.UseHttpsRedirection(); //使用Ocelot中间件 //app.UseOcelot().Wait(); app.UseOcelot((builder, config) => { //自定义中间件 app.UseBuildOcelotPipeline(config); }).Wait(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }