├── GoodApi ├── appsettings.json ├── appsettings.Development.json ├── Controllers │ ├── HealthController.cs │ ├── GoodController.cs │ └── ValuesController.cs ├── GoodApi.csproj ├── Program.cs └── Startup.cs ├── OrderApi ├── appsettings.json ├── appsettings.Development.json ├── Controllers │ ├── HealthController.cs │ ├── OrderController.cs │ └── ValuesController.cs ├── OrderApi.csproj ├── Program.cs └── Startup.cs ├── OcelotDemo.Auth ├── appsettings.json ├── appsettings.Development.json ├── OcelotDemo.Auth.csproj ├── Program.cs ├── Controllers │ └── ValuesController.cs ├── ApiConfig.cs ├── tempkey.rsa └── Startup.cs ├── OcelotDemo.Models ├── OcelotDemo.Models.csproj ├── Goods.cs └── Orders.cs ├── README.md ├── OcelotDemo ├── appsettings.Development.json ├── appsettings.json ├── OcelotDemo.csproj ├── IdentityServerOptions.cs ├── Controllers │ └── ValuesController.cs ├── Program.cs ├── Ocelot.json └── Startup.cs ├── Ocelot.ConfigAuthLimitCache ├── Ocelot.ConfigAuthLimitCache.csproj ├── Middleware │ ├── AhphResponderMiddlewareExtensions.cs │ ├── AhphResponderMiddleware.cs │ ├── OcelotPipelineExtensions.cs │ └── OcelotMiddlewareExtensions.cs ├── Core │ └── ErrorResult.cs ├── Models │ ├── OcelotGlobalConfiguration.cs │ └── OcelotReRoutes.cs ├── Configuration │ ├── ConfigAuthLimitCacheOptions.cs │ └── DataBaseMiddlewareConfigurationProvider.cs ├── DependencyInjection │ └── ServiceCollectionExtensions.cs ├── Extensions │ └── JsonExtensions.cs └── Repository │ └── SqlServerFileConfigurationRepository.cs ├── OcelotDemo.sln ├── .gitignore └── LICENSE /GoodApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*" 8 | } 9 | -------------------------------------------------------------------------------- /OrderApi/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*" 8 | } 9 | -------------------------------------------------------------------------------- /OcelotDemo.Auth/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "AllowedHosts": "*" 8 | } 9 | -------------------------------------------------------------------------------- /OcelotDemo.Models/OcelotDemo.Models.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.1 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # OcelotDemo 2 | Ocelot简易教程中使用的实例代码 3 | 4 | 对应的wiki教程: 5 | https://github.com/yilezhu/OcelotDemo/wiki/Ocelot%E7%AE%80%E6%98%93%E6%95%99%E7%A8%8B(%E4%B8%80)%E4%B9%8BOcelot%E6%98%AF%E4%BB%80%E4%B9%88 6 | -------------------------------------------------------------------------------- /GoodApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /OcelotDemo/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /OrderApi/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /OcelotDemo.Auth/appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Debug", 5 | "System": "Information", 6 | "Microsoft": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /OcelotDemo/appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Warning" 5 | } 6 | }, 7 | "IdentityServerOptions": { 8 | 9 | "ServerIP": "localhost", 10 | "ServerPort": 5003, 11 | "IdentityScheme": "Bearer", 12 | "ResourceName": "OcelotApi" 13 | }, 14 | "AllowedHosts": "*" 15 | } 16 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Ocelot.ConfigAuthLimitCache.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /OcelotDemo.Models/Goods.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace OcelotDemo.Models 6 | { 7 | /// 8 | /// yilezhu 9 | /// 2018.9.23 10 | /// 商品信息 11 | /// 12 | public class Goods 13 | { 14 | public int Id { get; set; } 15 | public string Content { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /OcelotDemo.Models/Orders.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace OcelotDemo.Models 6 | { 7 | /// 8 | /// yilezhu 9 | /// 2018.9.23 10 | /// 订单信息 11 | /// 12 | public class Orders 13 | { 14 | public int Id { get; set; } 15 | public string Content { get; set; } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /OcelotDemo.Auth/OcelotDemo.Auth.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /GoodApi/Controllers/HealthController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.AspNetCore.Mvc; 7 | 8 | namespace GoodApi.Controllers 9 | { 10 | [Route("[controller]")] 11 | [ApiController] 12 | public class HealthController : ControllerBase 13 | { 14 | [HttpGet] 15 | public IActionResult Get() => Ok(); 16 | } 17 | } -------------------------------------------------------------------------------- /OrderApi/Controllers/HealthController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.AspNetCore.Mvc; 7 | 8 | namespace OrderApi.Controllers 9 | { 10 | [Route("[controller]")] 11 | [ApiController] 12 | public class HealthController : ControllerBase 13 | { 14 | [HttpGet] 15 | public IActionResult Get() => Ok(); 16 | } 17 | } -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Middleware/AhphResponderMiddlewareExtensions.cs: -------------------------------------------------------------------------------- 1 | using Ocelot.Middleware.Pipeline; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Text; 5 | 6 | namespace Ocelot.ConfigAuthLimitCache.Middleware 7 | { 8 | public static class AhphResponderMiddlewareExtensions 9 | { 10 | public static IOcelotPipelineBuilder UseAhphResponderMiddleware(this IOcelotPipelineBuilder builder) 11 | { 12 | return builder.UseMiddleware(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Core/ErrorResult.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Ocelot.ConfigAuthLimitCache.Core 6 | { 7 | /// 8 | /// yilezhu 9 | /// 2018.10.22 10 | /// 输出的错误实体 11 | /// 12 | public class ErrorResult 13 | { 14 | /// 15 | /// 错误代码 16 | /// 17 | public int errcode { get; set; } 18 | 19 | /// 20 | /// 错误描述 21 | /// 22 | public string errmsg { get; set; } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /GoodApi/GoodApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /OrderApi/OrderApi.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /GoodApi/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace GoodApi 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | CreateWebHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseUrls("http://localhost:1001") 23 | .UseStartup(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /OrderApi/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace OrderApi 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | CreateWebHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseUrls("http://localhost:1002") 23 | .UseStartup(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /OcelotDemo.Auth/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | 11 | namespace OcelotDemo.Auth 12 | { 13 | public class Program 14 | { 15 | public static void Main(string[] args) 16 | { 17 | CreateWebHostBuilder(args).Build().Run(); 18 | } 19 | 20 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 21 | WebHost.CreateDefaultBuilder(args) 22 | .UseUrls("http://localhost:5003") 23 | .UseStartup(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /OrderApi/Controllers/OrderController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.AspNetCore.Mvc; 7 | using OcelotDemo.Models; 8 | using Newtonsoft.Json; 9 | 10 | namespace OrderApi.Controllers 11 | { 12 | [Route("api/[controller]")] 13 | [ApiController] 14 | public class OrderController : ControllerBase 15 | { 16 | // GET api/Order/5 17 | [HttpGet("{id}")] 18 | public ActionResult Get(int id) 19 | { 20 | var item = new Orders { 21 | Id=id, 22 | Content=$"{id}的订单明细", 23 | }; 24 | return JsonConvert.SerializeObject(item); 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /GoodApi/Controllers/GoodController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Http; 6 | using Microsoft.AspNetCore.Mvc; 7 | using Newtonsoft.Json; 8 | using OcelotDemo.Models; 9 | 10 | namespace GoodApi.Controllers 11 | { 12 | [Route("api/[controller]")] 13 | [ApiController] 14 | public class GoodController : ControllerBase 15 | { 16 | // GET api/Good/5 17 | [HttpGet("{id}")] 18 | public ActionResult Get(int id) 19 | { 20 | var item = new Goods 21 | { 22 | Id = id, 23 | Content = $"{id}的关联的商品明细", 24 | }; 25 | return JsonConvert.SerializeObject(item); 26 | } 27 | } 28 | } -------------------------------------------------------------------------------- /OcelotDemo/OcelotDemo.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netcoreapp2.1 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | Always 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /OcelotDemo/IdentityServerOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | 6 | namespace OcelotDemo 7 | { 8 | /// 9 | /// yilezhu 10 | /// 2018.10.16 11 | /// IdentityServer的配置选项 12 | /// 13 | public class IdentityServerOptions 14 | { 15 | /// 16 | /// 授权服务器的Ip地址 17 | /// 18 | public string ServerIP { get; set; } 19 | /// 20 | /// 授权服务器的端口号 21 | /// 22 | public int ServerPort { get; set; } 23 | /// 24 | /// access_token的类型,获取access_token的时候返回参数中的token_type一致 25 | /// 26 | public string IdentityScheme { get; set; } 27 | /// 28 | /// 资源名称,认证服务注册的资源列表名称一致, 29 | /// 30 | public string ResourceName { get; set; } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /OcelotDemo.Auth/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace OcelotDemo.Auth.Controllers 8 | { 9 | [Route("api/[controller]")] 10 | [ApiController] 11 | public class ValuesController : ControllerBase 12 | { 13 | // GET api/values 14 | [HttpGet] 15 | public ActionResult> Get() 16 | { 17 | return new string[] { "value1", "value2" }; 18 | } 19 | 20 | // GET api/values/5 21 | [HttpGet("{id}")] 22 | public ActionResult Get(int id) 23 | { 24 | return "value"; 25 | } 26 | 27 | // POST api/values 28 | [HttpPost] 29 | public void Post([FromBody] string value) 30 | { 31 | } 32 | 33 | // PUT api/values/5 34 | [HttpPut("{id}")] 35 | public void Put(int id, [FromBody] string value) 36 | { 37 | } 38 | 39 | // DELETE api/values/5 40 | [HttpDelete("{id}")] 41 | public void Delete(int id) 42 | { 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /GoodApi/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace GoodApi.Controllers 8 | { 9 | [Route("api/[controller]")] 10 | [ApiController] 11 | public class ValuesController : ControllerBase 12 | { 13 | // GET api/values 14 | [HttpGet] 15 | public ActionResult> Get() 16 | { 17 | return new string[] { "value1 from Good Api", "value2 from Good Api" }; 18 | } 19 | 20 | // GET api/values/5 21 | [HttpGet("{id}")] 22 | public ActionResult Get(int id) 23 | { 24 | return "value"; 25 | } 26 | 27 | // POST api/values 28 | [HttpPost] 29 | public void Post([FromBody] string value) 30 | { 31 | } 32 | 33 | // PUT api/values/5 34 | [HttpPut("{id}")] 35 | public void Put(int id, [FromBody] string value) 36 | { 37 | } 38 | 39 | // DELETE api/values/5 40 | [HttpDelete("{id}")] 41 | public void Delete(int id) 42 | { 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /OcelotDemo/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace OcelotDemo.Controllers 8 | { 9 | [Route("api/[controller]")] 10 | [ApiController] 11 | public class ValuesController : ControllerBase 12 | { 13 | // GET api/values 14 | [HttpGet] 15 | public ActionResult> Get() 16 | { 17 | return new string[] { "value1 from Ocelot", "value2 from Ocelot" }; 18 | } 19 | 20 | // GET api/values/5 21 | [HttpGet("{id}")] 22 | public ActionResult Get(int id) 23 | { 24 | return "value"; 25 | } 26 | 27 | // POST api/values 28 | [HttpPost] 29 | public void Post([FromBody] string value) 30 | { 31 | } 32 | 33 | // PUT api/values/5 34 | [HttpPut("{id}")] 35 | public void Put(int id, [FromBody] string value) 36 | { 37 | } 38 | 39 | // DELETE api/values/5 40 | [HttpDelete("{id}")] 41 | public void Delete(int id) 42 | { 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /OrderApi/Controllers/ValuesController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Mvc; 6 | 7 | namespace OrderApi.Controllers 8 | { 9 | [Route("api/[controller]")] 10 | [ApiController] 11 | public class ValuesController : ControllerBase 12 | { 13 | // GET api/values 14 | [HttpGet] 15 | public ActionResult> Get() 16 | { 17 | return new string[] { "value1 from Order Api", "value2 from Order Api" }; 18 | } 19 | 20 | // GET api/values/5 21 | [HttpGet("{id}")] 22 | public ActionResult Get(int id) 23 | { 24 | return "value"; 25 | } 26 | 27 | // POST api/values 28 | [HttpPost] 29 | public void Post([FromBody] string value) 30 | { 31 | } 32 | 33 | // PUT api/values/5 34 | [HttpPut("{id}")] 35 | public void Put(int id, [FromBody] string value) 36 | { 37 | } 38 | 39 | // DELETE api/values/5 40 | [HttpDelete("{id}")] 41 | public void Delete(int id) 42 | { 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Models/OcelotGlobalConfiguration.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace Ocelot.ConfigAuthLimitCache.Models 7 | { 8 | /// 9 | /// yilezhu 10 | /// 2018.10.22 11 | /// 全局配置相关 12 | /// 13 | public class OcelotGlobalConfiguration 14 | { 15 | [Key] 16 | public int Id { get; set; } 17 | 18 | [Required] 19 | [StringLength(200)] 20 | public string GatewayName { get; set; } 21 | 22 | [StringLength(100)] 23 | public string RequestIdKey { get; set; } 24 | 25 | [StringLength(100)] 26 | public string BaseUrl { get; set; } 27 | 28 | [StringLength(50)] 29 | public string DownstreamScheme { get; set; } 30 | 31 | [StringLength(300)] 32 | public string ServiceDiscoveryProvider { get; set; } 33 | 34 | [StringLength(300)] 35 | public string QoSOptions { get; set; } 36 | 37 | [StringLength(300)] 38 | public string LoadBalancerOptions { get; set; } 39 | 40 | [StringLength(300)] 41 | public string HttpHandlerOptions { get; set; } 42 | 43 | public DateTime? LastUpdateTime { get; set; } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /GoodApi/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.Logging; 11 | using Microsoft.Extensions.Options; 12 | 13 | namespace GoodApi 14 | { 15 | public class Startup 16 | { 17 | public Startup(IConfiguration configuration) 18 | { 19 | Configuration = configuration; 20 | } 21 | 22 | public IConfiguration Configuration { get; } 23 | 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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 28 | } 29 | 30 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 31 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 32 | { 33 | if (env.IsDevelopment()) 34 | { 35 | app.UseDeveloperExceptionPage(); 36 | } 37 | 38 | app.UseMvc(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /OrderApi/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.Logging; 11 | using Microsoft.Extensions.Options; 12 | 13 | namespace OrderApi 14 | { 15 | public class Startup 16 | { 17 | public Startup(IConfiguration configuration) 18 | { 19 | Configuration = configuration; 20 | } 21 | 22 | public IConfiguration Configuration { get; } 23 | 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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 28 | } 29 | 30 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 31 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 32 | { 33 | if (env.IsDevelopment()) 34 | { 35 | app.UseDeveloperExceptionPage(); 36 | } 37 | 38 | app.UseMvc(); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /OcelotDemo/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | using Microsoft.AspNetCore; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.Logging; 10 | using Ocelot.DependencyInjection; 11 | 12 | namespace OcelotDemo 13 | { 14 | public class Program 15 | { 16 | public static void Main(string[] args) 17 | { 18 | CreateWebHostBuilder(args).Build().Run(); 19 | } 20 | 21 | public static IWebHostBuilder CreateWebHostBuilder(string[] args) => 22 | WebHost.CreateDefaultBuilder(args) 23 | .ConfigureAppConfiguration((hostingContext, config) => 24 | { 25 | config 26 | .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath) 27 | .AddJsonFile("appsettings.json", true, true) 28 | .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true) 29 | //.AddJsonFile("Ocelot.json", true, true) 30 | 31 | // .AddOcelot(hostingContext.HostingEnvironment) 32 | .AddEnvironmentVariables(); 33 | }) 34 | .UseUrls("http://localhost:1000") 35 | .UseStartup(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Configuration/ConfigAuthLimitCacheOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | 5 | namespace Ocelot.ConfigAuthLimitCache.Configuration 6 | { 7 | /// 8 | /// yilezhu 9 | /// 2018.10.22 10 | /// 重写管道需要传入的配置项 11 | /// 12 | public class ConfigAuthLimitCacheOptions 13 | { 14 | /// 15 | /// 是否启动限流,默认 true 16 | /// 17 | public bool EnableRateLimit { get; set; } = true; 18 | 19 | /// 20 | /// 是否启动授权,默认 true 21 | /// 22 | public bool EnableAuthorization { get; set; } = true; 23 | 24 | /// 25 | /// 限流校验的头部标识,默认 client_id 26 | /// 27 | public string ClientKey { get; set; } = "client_id"; 28 | 29 | /// 30 | /// 提取数据缓存过期时间(秒),默认1个小时 31 | /// 32 | public int CacheExpireTime { get; set; } = 3600; 33 | 34 | /// 35 | /// 缓存默认前缀,防止重复 36 | /// 37 | public string CachePrefix { get; set; } = "oce"; 38 | 39 | /// 40 | /// 数据库连接字符串,使用不同数据库时自行修改,默认实现了SQLSERVER 41 | /// 42 | public string DbConnectionStrings { get; set; } 43 | 44 | /// 45 | /// Redis连接字符串,需要传入,数组形式,多个则采用集群模式 46 | /// 47 | public List RedisConnectionStrings { get; set; } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /OcelotDemo.Auth/ApiConfig.cs: -------------------------------------------------------------------------------- 1 | using IdentityServer4.Models; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Threading.Tasks; 6 | 7 | namespace OcelotDemo.Auth 8 | { 9 | /// 10 | /// yilezhu 11 | /// 2018.10.16 12 | /// 因为此处采用in-memory,所以硬编码一些api,以及client 13 | /// 14 | public class ApiConfig 15 | { 16 | /// 17 | /// 定义ApiResource 这里的资源(Resources)指的就是我们的API 18 | /// 19 | /// ApiResource枚举 20 | public static IEnumerable GetApiResources() 21 | { 22 | return new[] 23 | { 24 | new ApiResource("OcelotApi", "OcelotDemo的APi") 25 | }; 26 | } 27 | 28 | /// 29 | /// 定义受信任的客户端 Client 30 | /// 31 | /// 32 | public static IEnumerable GetClients() 33 | { 34 | return new[] 35 | { 36 | new Client 37 | { 38 | ClientId = "OcelotDemo",//客户端的标识,要是惟一的 39 | ClientSecrets = new [] { new Secret("yilezhu123".Sha256()) },//客户端密码,进行了加密 40 | AllowedGrantTypes = GrantTypes.ClientCredentials,//授权方式,这里采用的是客户端认证模式,只要ClientId,以及ClientSecrets正确即可访问对应的AllowedScopes里面的api资源 41 | AllowedScopes = new [] { "OcelotApi" }//定义这个客户端可以访问的APi资源数组,上面只有一个api 42 | } 43 | }; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /OcelotDemo.Auth/tempkey.rsa: -------------------------------------------------------------------------------- 1 | {"KeyId":"ff13937dbc79a4475280d731b1a0ab2c","Parameters":{"D":"SvihRqALvb3+EPAxFd1KBzuwhbVHRNMazGZ/XPdP1JGc/8HMRfFS9terEtK1kVPjAL4uchMioc9MOjrmjgGlj4uzEbEhtYvIGThj35xQbXnCNfutuJ8dsUBKi8Om4+aPNZh2ZLXD8qmxHJuB6BLyQRJpvr9sHD8nsfMLFM3/LLOZ0+/G9xRZL851AYXwPXlBY2u/5BYBU9mVQ0QlNxv3fRjfGDGciwCNKCxqMO9QAXNb4hUaWOI94USQrIsl7D/60WV5fu6uphMeB/BY+W4hI9Kc4ipC8Tw/eFWDOlFJKbotInK9uPTX2OGkcswJLQvwGn1xpZuqqmsZMIslF4wiWQ==","DP":"gWQTGpyNQx42MtPLacK7BMcVWeKtamafaSWeKmCszEytg4r/+4IEwbEdnLv6sV9TyvBjl9MuZcy0ymtFJ0jMZ4bHpgTU9Dss1CAYDx7DZH8YMbF5S85+QB3gNQaea2H2DKJMjF5AYWRtX4JONVYE0Yy5vvACOuSVuR+mODEfjuc=","DQ":"gJZyhw2N+EKXQ6CuMVMvhZ+kzCt8m0wzFoq+PN+g2c3J5BEZRQyTuCVPfsE1VvLnyqc0pFJ21jNv8zwEagrENH70p5ylysW0qoQgWVC0XJFM+o95WGBcherDiGhLFnghJh8GS0ZkGLRr5ovgsnZy0kuY6nnex4XOTofSvOpOFJ0=","Exponent":"AQAB","InverseQ":"Uw7ydiT+jK+kOjm+/XsUSvUwESHvaLiD98Yup3SzQy0a1vA9ljmycg2nbEr77t3rJbrEl2Uvawodwm4vrbD7UmX1zGaKtthHRKNUmNNkv7DZvGQSSAsnN1hbPIRklrZ4k4W+IarcGm4RaMuxvtIVRsrLmbXi5c/WlGV/AXY+YUM=","Modulus":"syaXBUIW8QaDc/h6EsPnxfUO2rxpKP/UFlbq/jbRYkPuKnDVCqMiEkhDwJTUCUXqkxSyGV3QvYovGJQCslwkrQfYsoJf5+6BHsBenI4atmksyHqmE7i+3ovJhq0Bnra32ReKb+/ziJMkcYwOJZGd4QRDlytICdAPGCnwWr0S0wXcRYsl6f7WKpR1Lmo0LjY8LlSxTUbxoDgv+SnaRXKmBE+Cofku9UMQWYd/7Fpfsg5EpdDMIhXtHG0wfbVofUaROErOcgZCxRdg+EvIg3srMfGVbPoItlTn/ZAKMA4sgk9n3MFsNHfmcezcBVB/+goBU12YEc+FzHlXTfaMAB+tVQ==","P":"0CQ4xTPFDstohYbA1AWij1Eg2bbXi/Rsp41iBI36nWNi78XPmChEVqzVDPkacY6p72zNxsyLhvJ5oeJ6GzhheSLmcxserUoyc/Aqn3ubm84JhLBJRlfyERrQa4R8c/KDB3+e+Q/IZoc6UVH+LO3cN+8HpSAFstex0VJOAOnMaW8=","Q":"3FfkrHqa7T+gFV2FQSMX0ihB8XauXwbGwxaCQM5AghzcQXStROpU4Oip/SPPl/Usw2PnEfkIenrM1tyJEfJOhfjAfurswku9cPOcAjPYhE06CCRwV8bX686+1v6QcAtLzIqcq5lzgrNxlPuQV1TJ4ZnTMbKof5UMyW90l66Sy3s="}} -------------------------------------------------------------------------------- /OcelotDemo/Ocelot.json: -------------------------------------------------------------------------------- 1 | { 2 | "ReRoutes": [ 3 | { 4 | "DownstreamPathTemplate": "/api/{everything}", 5 | "DownstreamScheme": "http", 6 | "DownstreamHostAndPorts": [ 7 | { 8 | "Host": "localhost", 9 | "Port": 1001 10 | }, 11 | { 12 | "Host": "localhost", 13 | "Port": 1002 14 | } 15 | ], 16 | "UpstreamPathTemplate": "/{everything}", 17 | "UpstreamHttpMethod": [ "Get", "Post" ], 18 | "LoadBalancerOptions": { 19 | "Type": "RoundRobin" 20 | }, 21 | "AuthenticationOptions": { 22 | "AuthenticationProviderKey": "OcelotKey", 23 | "AllowedScopes": [] 24 | } 25 | } 26 | ], 27 | "Aggregates": [], 28 | "GlobalConfiguration": { 29 | "RequestIdKey": null, 30 | "ServiceDiscoveryProvider": { 31 | "Host": "localhost", 32 | "Port": 8500, 33 | "Type": "Consul", 34 | "Token": null, 35 | "ConfigurationKey": null 36 | }, 37 | "RateLimitOptions": { 38 | "ClientIdHeader": "ClientId", 39 | "QuotaExceededMessage": null, 40 | "RateLimitCounterPrefix": "ocelot", 41 | "DisableRateLimitHeaders": false, 42 | "HttpStatusCode": 429 43 | }, 44 | "QoSOptions": { 45 | "ExceptionsAllowedBeforeBreaking": 0, 46 | "DurationOfBreak": 0, 47 | "TimeoutValue": 0 48 | }, 49 | "BaseUrl": null, 50 | "LoadBalancerOptions": { 51 | "Type": "LeastConnection", 52 | "Key": null, 53 | "Expiry": 0 54 | }, 55 | "DownstreamScheme": "http", 56 | "HttpHandlerOptions": { 57 | "AllowAutoRedirect": false, 58 | "UseCookieContainer": false, 59 | "UseTracing": false 60 | } 61 | } 62 | } -------------------------------------------------------------------------------- /OcelotDemo.Auth/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Builder; 6 | using Microsoft.AspNetCore.Hosting; 7 | using Microsoft.AspNetCore.Mvc; 8 | using Microsoft.Extensions.Configuration; 9 | using Microsoft.Extensions.DependencyInjection; 10 | using Microsoft.Extensions.Logging; 11 | using Microsoft.Extensions.Options; 12 | 13 | namespace OcelotDemo.Auth 14 | { 15 | public class Startup 16 | { 17 | public Startup(IConfiguration configuration) 18 | { 19 | Configuration = configuration; 20 | } 21 | 22 | public IConfiguration Configuration { get; } 23 | 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 | //注入IdentityServer服务 28 | services.AddIdentityServer() 29 | .AddDeveloperSigningCredential() 30 | .AddInMemoryClients(ApiConfig.GetClients()) 31 | .AddInMemoryApiResources(ApiConfig.GetApiResources()); 32 | services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 33 | } 34 | 35 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 36 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 37 | { 38 | if (env.IsDevelopment()) 39 | { 40 | app.UseDeveloperExceptionPage(); 41 | } 42 | //添加认证中间件 43 | app.UseIdentityServer(); 44 | app.UseMvc(); 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/DependencyInjection/ServiceCollectionExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Options; 3 | using Ocelot.Cache; 4 | using Ocelot.ConfigAuthLimitCache.Configuration; 5 | using Ocelot.ConfigAuthLimitCache.Repository; 6 | using Ocelot.Configuration.File; 7 | using Ocelot.Configuration.Repository; 8 | using Ocelot.DependencyInjection; 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Text; 12 | 13 | namespace Ocelot.ConfigAuthLimitCache.DependencyInjection 14 | { 15 | /// 16 | /// yilezhu 17 | /// 2018.10.22 18 | /// 基于Ocelot扩展的依赖注入 19 | /// 20 | public static class ServiceCollectionExtensions 21 | { 22 | /// 23 | /// 添加默认的注入方式,所有需要传入的参数都是用默认值 24 | /// 25 | /// 26 | /// 27 | public static IOcelotBuilder AddAuthLimitCache(this IOcelotBuilder builder, Action option) 28 | { 29 | builder.Services.Configure(option); 30 | builder.Services.AddSingleton( 31 | resolver => resolver.GetRequiredService>().Value); 32 | #region 注入其他配置信息 33 | //重写提取Ocelot配置信息 34 | builder.Services.AddSingleton(DataBaseConfigurationProvider.Get); 35 | //builder.Services.AddHostedService(); 36 | builder.Services.AddSingleton(); 37 | //注入自定义限流配置 38 | //注入认证信息 39 | #endregion 40 | return builder; 41 | } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Extensions/JsonExtensions.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | using Newtonsoft.Json.Converters; 3 | using Newtonsoft.Json.Linq; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Data; 7 | using System.Text; 8 | 9 | namespace Ocelot.ConfigAuthLimitCache.Extensions 10 | { 11 | /// 12 | /// yilezhu 13 | /// 2018.10.22 14 | /// json扩展方法 15 | /// 16 | public static class JsonExtensions 17 | { 18 | /// 19 | /// string转换成Object 20 | /// 21 | /// json字符串 22 | /// 23 | public static object ToObject(this string Json) 24 | { 25 | return Json == null ? null : JsonConvert.DeserializeObject(Json); 26 | } 27 | 28 | /// 29 | /// obejct转换成json字符串 30 | /// 31 | /// 32 | /// 33 | public static string ToJson(this object obj) 34 | { 35 | var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" }; 36 | //var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd" }; 37 | return JsonConvert.SerializeObject(obj, timeConverter); 38 | } 39 | public static string ToJson(this object obj, string datetimeformats) 40 | { 41 | var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats }; 42 | return JsonConvert.SerializeObject(obj, timeConverter); 43 | } 44 | public static T ToObject(this string Json) 45 | { 46 | return Json == null ? default(T) : JsonConvert.DeserializeObject(Json); 47 | } 48 | public static List ToList(this string Json) 49 | { 50 | return Json == null ? null : JsonConvert.DeserializeObject>(Json); 51 | } 52 | public static DataTable ToDataTable(this string Json) 53 | { 54 | return Json == null ? null : JsonConvert.DeserializeObject(Json); 55 | } 56 | public static JObject ToJObject(this string Json) 57 | { 58 | return Json == null ? JObject.Parse("{}") : JObject.Parse(Json.Replace(" ", "")); 59 | } 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Models/OcelotReRoutes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel.DataAnnotations; 4 | using System.Text; 5 | 6 | namespace Ocelot.ConfigAuthLimitCache.Models 7 | { 8 | /// 9 | /// yilezhu 10 | /// 2018.10.22 11 | /// ReRoute的数据存储定义 12 | /// 13 | public class OcelotReRoutes 14 | { 15 | [Key] 16 | public int Id { get; set; } 17 | /// 18 | /// Ocelot 19 | /// 20 | [Required] 21 | public int OcelotGlobalConfigurationId { get; set; } 22 | 23 | [Required] 24 | [StringLength(150)] 25 | public string UpstreamPathTemplate { get; set; } 26 | 27 | [Required] 28 | [StringLength(50)] 29 | public string UpstreamHttpMethod { get; set; } 30 | 31 | [StringLength(100)] 32 | public string UpstreamHost { get; set; } 33 | 34 | [StringLength(50)] 35 | public string DownstreamScheme { get; set; } 36 | 37 | [StringLength(200)] 38 | public string DownstreamPathTemplate { get; set; } 39 | 40 | [StringLength(500)] 41 | public string DownstreamHostAndPorts { get; set; } 42 | 43 | [StringLength(300)] 44 | public string AuthenticationOptions { get; set; } 45 | 46 | [StringLength(100)] 47 | public string RequestIdKey { get; set; } 48 | 49 | [StringLength(200)] 50 | public string CacheOptions { get; set; } 51 | 52 | [StringLength(100)] 53 | public string ServiceName { get; set; } 54 | 55 | [StringLength(200)] 56 | public string QoSOptions { get; set; } 57 | 58 | [StringLength(200)] 59 | public string LoadBalancerOptions { get; set; } 60 | 61 | [StringLength(100)] 62 | public string Key { get; set; } 63 | 64 | [StringLength(200)] 65 | public string DelegatingHandlers { get; set; } 66 | 67 | public int? Priority { get; set; } 68 | 69 | public int? Timeout { get; set; } 70 | 71 | [StringLength(50)] 72 | public string CreateUid { get; set; } 73 | 74 | public DateTime? CreateTime { get; set; } 75 | 76 | [StringLength(50)] 77 | public string UpdateUid { get; set; } 78 | 79 | public DateTime? UpdateTime { get; set; } 80 | 81 | public int IsStatus { get; set; } 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /OcelotDemo/Startup.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using IdentityServer4.AccessTokenValidation; 6 | using Microsoft.AspNetCore.Builder; 7 | using Microsoft.AspNetCore.Hosting; 8 | using Microsoft.AspNetCore.Mvc; 9 | using Microsoft.Extensions.Configuration; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Microsoft.Extensions.Logging; 12 | using Microsoft.Extensions.Options; 13 | using Ocelot.DependencyInjection; 14 | using Ocelot.Middleware; 15 | using Ocelot.Provider.Consul; 16 | using Ocelot.ConfigAuthLimitCache.DependencyInjection; 17 | using Ocelot.ConfigAuthLimitCache.Middleware; 18 | 19 | namespace OcelotDemo 20 | { 21 | public class Startup 22 | { 23 | public Startup(IConfiguration configuration) 24 | { 25 | Configuration = configuration; 26 | } 27 | 28 | public IConfiguration Configuration { get; } 29 | 30 | // This method gets called by the runtime. Use this method to add services to the container. 31 | public void ConfigureServices(IServiceCollection services) 32 | { 33 | //var authenticationProviderKey = "OcelotKey"; 34 | //var identityServerOptions = new IdentityServerOptions(); 35 | //Configuration.Bind("IdentityServerOptions", identityServerOptions); 36 | //services.AddAuthentication(identityServerOptions.IdentityScheme) 37 | // .AddIdentityServerAuthentication(authenticationProviderKey, options => 38 | // { 39 | // options.RequireHttpsMetadata = false; //是否启用https 40 | // options.Authority = $"http://{identityServerOptions.ServerIP}:{identityServerOptions.ServerPort}";//配置授权认证的地址 41 | // options.ApiName = identityServerOptions.ResourceName; //资源名称,跟认证服务中注册的资源列表名称中的apiResource一致 42 | // options.SupportedTokens = SupportedTokens.Both; 43 | // } 44 | // ); 45 | services.AddOcelot()//注入Ocelot服务 46 | .AddAuthLimitCache(option=> { 47 | option.DbConnectionStrings = "Server=.;Database=Ocelot;User ID=sa;Password=1;"; 48 | }) 49 | .AddConsul(); 50 | //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); 51 | } 52 | 53 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 54 | public void Configure(IApplicationBuilder app, IHostingEnvironment env) 55 | { 56 | if (env.IsDevelopment()) 57 | { 58 | app.UseDeveloperExceptionPage(); 59 | } 60 | //app.UseAuthentication(); 61 | app.UseAhphOcelot().Wait(); 62 | //app.UseOcelot().Wait();//使用Ocelot中间件 63 | //app.UseMvc(); 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Middleware/AhphResponderMiddleware.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Http; 2 | using Ocelot.Errors; 3 | using Ocelot.Middleware; 4 | using Ocelot.Responder; 5 | using System; 6 | using System.Collections.Generic; 7 | using System.Net; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using Ocelot.DependencyInjection; 11 | using Ocelot.Logging; 12 | using Ocelot.ConfigAuthLimitCache.Core; 13 | using Ocelot.ConfigAuthLimitCache.Extensions; 14 | 15 | namespace Ocelot.ConfigAuthLimitCache.Middleware 16 | { 17 | /// 18 | /// yilezhu 19 | /// 2018.10.22 20 | /// 重写请求中间件,修复bug,并指定统一的状态码返回,请求结束时捕获最终的结果,输出或返回 21 | /// 22 | public class AhphResponderMiddleware: OcelotMiddleware 23 | { 24 | private readonly OcelotRequestDelegate _next; 25 | private readonly IHttpResponder _responder; 26 | private readonly IErrorsToHttpStatusCodeMapper _codeMapper; 27 | 28 | public AhphResponderMiddleware(OcelotRequestDelegate next, 29 | IHttpResponder responder, 30 | IOcelotLoggerFactory loggerFactory, 31 | IErrorsToHttpStatusCodeMapper codeMapper 32 | ) 33 | : base(loggerFactory.CreateLogger()) 34 | { 35 | _next = next; 36 | _responder = responder; 37 | _codeMapper = codeMapper; 38 | } 39 | 40 | public async Task Invoke(DownstreamContext context) 41 | { 42 | await _next.Invoke(context); 43 | 44 | if (context.IsError) 45 | { 46 | // Logger.LogWarning($"{context.Errors.ToErrorString()} errors found in {MiddlewareName}. Setting error response for request path:{context.HttpContext.Request.Path}, request method: {context.HttpContext.Request.Method}"); 47 | 48 | // SetErrorResponse(context.HttpContext, context.Errors); 49 | 50 | var errmsg = context.Errors[0].Message; 51 | int httpstatus = _codeMapper.Map(context.Errors); 52 | var errResult = new ErrorResult() { errcode = httpstatus, errmsg = errmsg }; 53 | var message = errResult.ToJson(); 54 | context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK; 55 | await context.HttpContext.Response.WriteAsync(message); 56 | return; 57 | 58 | } 59 | else if (context.DownstreamResponse == null) 60 | {//添加如果管道强制终止,不做任何处理,修复未将对象实例化错误 61 | 62 | } 63 | else 64 | { 65 | Logger.LogDebug("no pipeline errors, setting and returning completed response"); 66 | await _responder.SetResponseOnHttpContext(context.HttpContext, context.DownstreamResponse); 67 | } 68 | } 69 | 70 | private void SetErrorResponse(HttpContext context, List errors) 71 | { 72 | var statusCode = _codeMapper.Map(errors); 73 | _responder.SetErrorResponseOnContext(context, statusCode); 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /OcelotDemo.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27703.2026 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OcelotDemo", "OcelotDemo\OcelotDemo.csproj", "{C5D4A187-90F1-4458-A40B-F12345C2D4D1}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GoodApi", "GoodApi\GoodApi.csproj", "{C036C7C5-6C45-422A-97B5-68D620567C20}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OrderApi", "OrderApi\OrderApi.csproj", "{93340FC0-C6BB-4109-87B3-EA3D27D06C3D}" 11 | EndProject 12 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OcelotDemo.Models", "OcelotDemo.Models\OcelotDemo.Models.csproj", "{39F3E1FE-19DF-4DB4-902F-8EC6AC713A80}" 13 | EndProject 14 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OcelotDemo.Auth", "OcelotDemo.Auth\OcelotDemo.Auth.csproj", "{9594A4BD-E561-4162-849A-02C3F0A70308}" 15 | EndProject 16 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Ocelot.ConfigAuthLimitCache", "Ocelot.ConfigAuthLimitCache\Ocelot.ConfigAuthLimitCache.csproj", "{252D54E0-1D54-482B-8692-A7CF00031917}" 17 | EndProject 18 | Global 19 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 20 | Debug|Any CPU = Debug|Any CPU 21 | Release|Any CPU = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 24 | {C5D4A187-90F1-4458-A40B-F12345C2D4D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {C5D4A187-90F1-4458-A40B-F12345C2D4D1}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {C5D4A187-90F1-4458-A40B-F12345C2D4D1}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {C5D4A187-90F1-4458-A40B-F12345C2D4D1}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {C036C7C5-6C45-422A-97B5-68D620567C20}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {C036C7C5-6C45-422A-97B5-68D620567C20}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {C036C7C5-6C45-422A-97B5-68D620567C20}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {C036C7C5-6C45-422A-97B5-68D620567C20}.Release|Any CPU.Build.0 = Release|Any CPU 32 | {93340FC0-C6BB-4109-87B3-EA3D27D06C3D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {93340FC0-C6BB-4109-87B3-EA3D27D06C3D}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {93340FC0-C6BB-4109-87B3-EA3D27D06C3D}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {93340FC0-C6BB-4109-87B3-EA3D27D06C3D}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {39F3E1FE-19DF-4DB4-902F-8EC6AC713A80}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {39F3E1FE-19DF-4DB4-902F-8EC6AC713A80}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {39F3E1FE-19DF-4DB4-902F-8EC6AC713A80}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {39F3E1FE-19DF-4DB4-902F-8EC6AC713A80}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {9594A4BD-E561-4162-849A-02C3F0A70308}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {9594A4BD-E561-4162-849A-02C3F0A70308}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {9594A4BD-E561-4162-849A-02C3F0A70308}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {9594A4BD-E561-4162-849A-02C3F0A70308}.Release|Any CPU.Build.0 = Release|Any CPU 44 | {252D54E0-1D54-482B-8692-A7CF00031917}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 45 | {252D54E0-1D54-482B-8692-A7CF00031917}.Debug|Any CPU.Build.0 = Debug|Any CPU 46 | {252D54E0-1D54-482B-8692-A7CF00031917}.Release|Any CPU.ActiveCfg = Release|Any CPU 47 | {252D54E0-1D54-482B-8692-A7CF00031917}.Release|Any CPU.Build.0 = Release|Any CPU 48 | EndGlobalSection 49 | GlobalSection(SolutionProperties) = preSolution 50 | HideSolutionNode = FALSE 51 | EndGlobalSection 52 | GlobalSection(ExtensibilityGlobals) = postSolution 53 | SolutionGuid = {5A4BCC1B-F36C-4D4C-9BB0-5D15F2B6F82D} 54 | EndGlobalSection 55 | EndGlobal 56 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Configuration/DataBaseMiddlewareConfigurationProvider.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.Extensions.Options; 3 | using Ocelot.Configuration.Creator; 4 | using Ocelot.Configuration.File; 5 | using Ocelot.Configuration.Repository; 6 | using System; 7 | using System.Linq; 8 | using System.Collections.Generic; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | using Ocelot.Responses; 12 | using Ocelot.Middleware; 13 | using Microsoft.Extensions.DependencyInjection; 14 | 15 | namespace Ocelot.ConfigAuthLimitCache.Configuration 16 | { 17 | /// 18 | /// yilezhu 19 | /// 2018.10.22 20 | /// 从数据库中加载配置的Provider 21 | /// 22 | public class DataBaseConfigurationProvider 23 | { 24 | public static OcelotMiddlewareConfigurationDelegate Get = async builder => 25 | { 26 | var fileConfigRepo = builder.ApplicationServices.GetService(); 27 | var fileConfig = builder.ApplicationServices.GetService>(); 28 | var internalConfigCreator = builder.ApplicationServices.GetService(); 29 | var internalConfigRepo = builder.ApplicationServices.GetService(); 30 | await SetFileConfigInDataBase(builder, fileConfigRepo, fileConfig, internalConfigCreator, internalConfigRepo); 31 | 32 | }; 33 | 34 | private static async Task SetFileConfigInDataBase(IApplicationBuilder builder, 35 | IFileConfigurationRepository fileConfigRepo, IOptionsMonitor fileConfig, 36 | IInternalConfigurationCreator internalConfigCreator, IInternalConfigurationRepository internalConfigRepo) 37 | { 38 | 39 | // get the config from consul. 40 | var fileConfigFromDataBase = await fileConfigRepo.Get(); 41 | 42 | if (IsError(fileConfigFromDataBase)) 43 | { 44 | ThrowToStopOcelotStarting(fileConfigFromDataBase); 45 | } 46 | //else if (ConfigNotStoredInDataBase(fileConfigFromDataBase)) 47 | //{ 48 | // //there was no config in consul set the file in config in consul 49 | // await fileConfigRepo.Set(fileConfig.CurrentValue); 50 | //} 51 | else 52 | { 53 | await fileConfigRepo.Set(fileConfigFromDataBase.Data); 54 | // create the internal config from consul data 55 | var internalConfig = await internalConfigCreator.Create(fileConfigFromDataBase.Data); 56 | 57 | if (IsError(internalConfig)) 58 | { 59 | ThrowToStopOcelotStarting(internalConfig); 60 | } 61 | else 62 | { 63 | // add the internal config to the internal repo 64 | var response = internalConfigRepo.AddOrReplace(internalConfig.Data); 65 | 66 | if (IsError(response)) 67 | { 68 | ThrowToStopOcelotStarting(response); 69 | } 70 | } 71 | 72 | if (IsError(internalConfig)) 73 | { 74 | ThrowToStopOcelotStarting(internalConfig); 75 | } 76 | } 77 | } 78 | 79 | private static void ThrowToStopOcelotStarting(Response config) 80 | { 81 | throw new Exception($"Unable to start Ocelot, errors are: {string.Join(",", config.Errors.Select(x => x.ToString()))}"); 82 | } 83 | 84 | private static bool IsError(Response response) 85 | { 86 | return response == null || response.IsError; 87 | } 88 | 89 | private static bool ConfigNotStoredInDataBase(Response fileConfigFromDataBase) 90 | { 91 | return fileConfigFromDataBase.Data == null; 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Middleware/OcelotPipelineExtensions.cs: -------------------------------------------------------------------------------- 1 | using Ocelot.DownstreamRouteFinder.Middleware; 2 | using Ocelot.Errors.Middleware; 3 | using Ocelot.Headers.Middleware; 4 | using Ocelot.LoadBalancer.Middleware; 5 | using Ocelot.Middleware; 6 | using Ocelot.Middleware.Pipeline; 7 | using Ocelot.Request.Middleware; 8 | using Ocelot.WebSockets.Middleware; 9 | using System; 10 | using System.Linq; 11 | using System.Collections.Generic; 12 | using System.Text; 13 | using System.Threading.Tasks; 14 | using Microsoft.Extensions.DependencyInjection; 15 | using Ocelot.DownstreamUrlCreator.Middleware; 16 | using Ocelot.Authentication.Middleware; 17 | using Ocelot.Requester.Middleware; 18 | using Ocelot.Cache.Middleware; 19 | using Ocelot.Authorisation.Middleware; 20 | 21 | namespace Ocelot.ConfigAuthLimitCache.Middleware 22 | { 23 | /// 24 | /// yilzhu 25 | /// 2018.10.22 26 | /// 重写Ocelot自定义管道,满足自身需要 27 | /// 28 | public static class OcelotPipelineExtensions 29 | { 30 | public static OcelotRequestDelegate BuildAhphOcelotPipeline(this IOcelotPipelineBuilder builder, 31 | OcelotPipelineConfiguration pipelineConfiguration) 32 | { 33 | // This is registered to catch any global exceptions that are not handled 34 | // It also sets the Request Id if anything is set globally 35 | builder.UseExceptionHandlerMiddleware(); 36 | 37 | // If the request is for websockets upgrade we fork into a different pipeline 38 | builder.MapWhen(context => context.HttpContext.WebSockets.IsWebSocketRequest, 39 | app => 40 | { 41 | app.UseDownstreamRouteFinderMiddleware(); 42 | app.UseDownstreamRequestInitialiser(); 43 | app.UseLoadBalancingMiddleware(); 44 | app.UseDownstreamUrlCreatorMiddleware(); 45 | app.UseWebSocketsProxyMiddleware(); 46 | }); 47 | 48 | // Allow the user to respond with absolutely anything they want. 49 | builder.UseIfNotNull(pipelineConfiguration.PreErrorResponderMiddleware); 50 | 51 | // 使用自定义的输出中间件 52 | builder.UseAhphResponderMiddleware(); 53 | 54 | // Then we get the downstream route information 55 | builder.UseDownstreamRouteFinderMiddleware(); 56 | 57 | // This security module, IP whitelist blacklist, extended security mechanism 58 | // builder.UseSecurityMiddleware(); 59 | 60 | //Expand other branch pipes 61 | if (pipelineConfiguration.MapWhenOcelotPipeline != null) 62 | { 63 | foreach (var pipeline in pipelineConfiguration.MapWhenOcelotPipeline) 64 | { 65 | builder.MapWhen(pipeline); 66 | } 67 | } 68 | 69 | // Now we have the ds route we can transform headers and stuff? 70 | builder.UseHttpHeadersTransformationMiddleware(); 71 | 72 | // Initialises downstream request 73 | builder.UseDownstreamRequestInitialiser(); 74 | 75 | // We check whether the request is ratelimit, and if there is no continue processing 76 | //移除自定义限流 77 | // builder.UseRateLimiting(); 78 | 79 | // This adds or updates the request id (initally we try and set this based on global config in the error handling middleware) 80 | // If anything was set at global level and we have a different setting at re route level the global stuff will be overwritten 81 | // This means you can get a scenario where you have a different request id from the first piece of middleware to the request id middleware. 82 | // builder.UseRequestIdMiddleware(); 83 | 84 | // Allow pre authentication logic. The idea being people might want to run something custom before what is built in. 85 | builder.UseIfNotNull(pipelineConfiguration.PreAuthenticationMiddleware); 86 | 87 | // Now we know where the client is going to go we can authenticate them. 88 | // We allow the ocelot middleware to be overriden by whatever the 89 | // user wants 90 | if (pipelineConfiguration.AuthenticationMiddleware == null) 91 | { 92 | builder.UseAuthenticationMiddleware(); 93 | } 94 | else 95 | { 96 | builder.Use(pipelineConfiguration.AuthenticationMiddleware); 97 | } 98 | 99 | // The next thing we do is look at any claims transforms in case this is important for authorisation 100 | // builder.UseClaimsToClaimsMiddleware(); 101 | 102 | // Allow pre authorisation logic. The idea being people might want to run something custom before what is built in. 103 | builder.UseIfNotNull(pipelineConfiguration.PreAuthorisationMiddleware); 104 | 105 | // Now we have authenticated and done any claims transformation we 106 | // can authorise the request 107 | // We allow the ocelot middleware to be overriden by whatever the 108 | // user wants 109 | if (pipelineConfiguration.AuthorisationMiddleware == null) 110 | { 111 | //使用自定义认证,移除默认的认证方式 112 | //builder.UseAuthorisationMiddleware(); 113 | } 114 | else 115 | { 116 | builder.Use(pipelineConfiguration.AuthorisationMiddleware); 117 | } 118 | 119 | // Now we can run the claims to headers transformation middleware 120 | // builder.UseClaimsToHeadersMiddleware(); 121 | 122 | // Allow the user to implement their own query string manipulation logic 123 | builder.UseIfNotNull(pipelineConfiguration.PreQueryStringBuilderMiddleware); 124 | 125 | // Now we can run any claims to query string transformation middleware 126 | // builder.UseClaimsToQueryStringMiddleware(); 127 | 128 | // Get the load balancer for this request 129 | builder.UseLoadBalancingMiddleware(); 130 | 131 | // This takes the downstream route we retrieved earlier and replaces any placeholders with the variables that should be used 132 | builder.UseDownstreamUrlCreatorMiddleware(); 133 | 134 | //应用授权、限流、缓存中间件 2018.10.07 135 | //builder.UseAuthLimitCacheMiddleware(); 136 | 137 | // Not sure if this is the best place for this but we use the downstream url 138 | // as the basis for our cache key. 139 | builder.UseOutputCacheMiddleware(); 140 | 141 | //We fire off the request and set the response on the scoped data repo 142 | builder.UseHttpRequesterMiddleware(); 143 | 144 | return builder.Build(); 145 | } 146 | 147 | private static void UseIfNotNull(this IOcelotPipelineBuilder builder, 148 | Func, Task> middleware) 149 | { 150 | if (middleware != null) 151 | { 152 | builder.Use(middleware); 153 | } 154 | } 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | 12 | # User-specific files (MonoDevelop/Xamarin Studio) 13 | *.userprefs 14 | 15 | # Build results 16 | [Dd]ebug/ 17 | [Dd]ebugPublic/ 18 | [Rr]elease/ 19 | [Rr]eleases/ 20 | x64/ 21 | x86/ 22 | bld/ 23 | [Bb]in/ 24 | [Oo]bj/ 25 | [Ll]og/ 26 | 27 | # Visual Studio 2015/2017 cache/options directory 28 | .vs/ 29 | # Uncomment if you have tasks that create the project's static files in wwwroot 30 | #wwwroot/ 31 | 32 | # Visual Studio 2017 auto generated files 33 | Generated\ Files/ 34 | 35 | # MSTest test Results 36 | [Tt]est[Rr]esult*/ 37 | [Bb]uild[Ll]og.* 38 | 39 | # NUNIT 40 | *.VisualState.xml 41 | TestResult.xml 42 | 43 | # Build Results of an ATL Project 44 | [Dd]ebugPS/ 45 | [Rr]eleasePS/ 46 | dlldata.c 47 | 48 | # Benchmark Results 49 | BenchmarkDotNet.Artifacts/ 50 | 51 | # .NET Core 52 | project.lock.json 53 | project.fragment.lock.json 54 | artifacts/ 55 | **/Properties/launchSettings.json 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Repository/SqlServerFileConfigurationRepository.cs: -------------------------------------------------------------------------------- 1 | using Dapper; 2 | using Ocelot.Cache; 3 | using Ocelot.ConfigAuthLimitCache.Configuration; 4 | using Ocelot.ConfigAuthLimitCache.Extensions; 5 | using Ocelot.ConfigAuthLimitCache.Models; 6 | using Ocelot.Configuration.File; 7 | using Ocelot.Configuration.Repository; 8 | using Ocelot.Logging; 9 | using Ocelot.Responses; 10 | using System; 11 | using System.Collections.Generic; 12 | using System.Data.SqlClient; 13 | using System.Text; 14 | using System.Threading.Tasks; 15 | 16 | namespace Ocelot.ConfigAuthLimitCache.Repository 17 | { 18 | /// 19 | /// yilezhu 20 | /// 2018.10.22 21 | /// 实现从SQLSERVER数据库中提取配置信息 22 | /// 23 | public class SqlServerFileConfigurationRepository : IFileConfigurationRepository 24 | { 25 | private readonly IOcelotCache _cache; 26 | private readonly IOcelotLogger _logger; 27 | private readonly ConfigAuthLimitCacheOptions _option; 28 | public SqlServerFileConfigurationRepository(ConfigAuthLimitCacheOptions option, IOcelotCache cache, IOcelotLoggerFactory loggerFactory) 29 | { 30 | _option = option; 31 | _cache = cache; 32 | _logger = loggerFactory.CreateLogger(); 33 | } 34 | 35 | public Task Set(FileConfiguration fileConfiguration) 36 | { 37 | _cache.AddAndDelete(_option.CachePrefix + "FileConfiguration", fileConfiguration, TimeSpan.FromSeconds(1800), ""); 38 | return Task.FromResult((Response)new OkResponse()); 39 | } 40 | 41 | /// 42 | /// 提取配置信息 43 | /// 44 | /// 45 | public async Task> Get() 46 | { 47 | var config = _cache.Get(_option.CachePrefix + "FileConfiguration", ""); 48 | 49 | if (config != null) 50 | { 51 | return new OkResponse(config); 52 | } 53 | #region 提取配置信息 54 | var file = new FileConfiguration(); 55 | string glbsql = "select top 1 * from OcelotGlobalConfiguration where IsDefault=1"; 56 | //提取全局配置信息 57 | using (var connection = new SqlConnection(_option.DbConnectionStrings)) 58 | { 59 | var result = await connection.QueryFirstOrDefaultAsync(glbsql); 60 | if (result != null) 61 | { 62 | var glb = new FileGlobalConfiguration(); 63 | glb.BaseUrl = result.BaseUrl; 64 | glb.DownstreamScheme = result.DownstreamScheme; 65 | glb.RequestIdKey = result.RequestIdKey; 66 | if (!String.IsNullOrEmpty(result.HttpHandlerOptions)) 67 | { 68 | glb.HttpHandlerOptions = result.HttpHandlerOptions.ToObject(); 69 | } 70 | if (!String.IsNullOrEmpty(result.LoadBalancerOptions)) 71 | { 72 | glb.LoadBalancerOptions = result.LoadBalancerOptions.ToObject(); 73 | } 74 | if (!String.IsNullOrEmpty(result.QoSOptions)) 75 | { 76 | glb.QoSOptions = result.QoSOptions.ToObject(); 77 | } 78 | if (!String.IsNullOrEmpty(result.ServiceDiscoveryProvider)) 79 | { 80 | glb.ServiceDiscoveryProvider = result.ServiceDiscoveryProvider.ToObject(); 81 | } 82 | file.GlobalConfiguration = glb; 83 | 84 | //提取路由信息 85 | 86 | string routesql = "select * from OcelotReRoutes where OcelotGlobalConfigurationId=@OcelotGlobalConfigurationId and IsStatus=1"; 87 | var routeresult = (await connection.QueryAsync(routesql, new { OcelotGlobalConfigurationId=result.Id })).AsList(); 88 | if (routeresult != null && routeresult.Count > 0) 89 | { 90 | var reroutelist = new List(); 91 | foreach (var model in routeresult) 92 | { 93 | var m = new FileReRoute(); 94 | if (!String.IsNullOrEmpty(model.AuthenticationOptions)) 95 | { 96 | m.AuthenticationOptions = model.AuthenticationOptions.ToObject(); 97 | } 98 | if (!String.IsNullOrEmpty(model.CacheOptions)) 99 | { 100 | m.FileCacheOptions = model.CacheOptions.ToObject(); 101 | } 102 | if (!String.IsNullOrEmpty(model.DelegatingHandlers)) 103 | { 104 | m.DelegatingHandlers = model.DelegatingHandlers.ToObject>(); 105 | } 106 | if (!String.IsNullOrEmpty(model.LoadBalancerOptions)) 107 | { 108 | m.LoadBalancerOptions = model.LoadBalancerOptions.ToObject(); 109 | } 110 | if (!String.IsNullOrEmpty(model.QoSOptions)) 111 | { 112 | m.QoSOptions = model.QoSOptions.ToObject(); 113 | } 114 | if (!String.IsNullOrEmpty(model.DownstreamHostAndPorts)) 115 | { 116 | m.DownstreamHostAndPorts = model.DownstreamHostAndPorts.ToObject>(); 117 | } 118 | //开始赋值 119 | m.DownstreamPathTemplate = model.DownstreamPathTemplate; 120 | m.DownstreamScheme = model.DownstreamScheme; 121 | m.Key = model.Key; 122 | m.Priority = model.Priority ?? 0; 123 | m.RequestIdKey = model.RequestIdKey; 124 | m.ServiceName = model.ServiceName; 125 | m.Timeout = model.Timeout ?? 0; 126 | m.UpstreamHost = model.UpstreamHost; 127 | if (!String.IsNullOrEmpty(model.UpstreamHttpMethod)) 128 | { 129 | m.UpstreamHttpMethod = model.UpstreamHttpMethod.ToObject>(); 130 | } 131 | m.UpstreamPathTemplate = model.UpstreamPathTemplate; 132 | reroutelist.Add(m); 133 | } 134 | file.ReRoutes = reroutelist; 135 | } 136 | } 137 | else 138 | { 139 | throw new Exception("未监测到配置信息"); 140 | } 141 | } 142 | #endregion 143 | if (file.ReRoutes == null || file.ReRoutes.Count == 0) 144 | { 145 | return new OkResponse(null); 146 | } 147 | return new OkResponse(file); 148 | } 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /Ocelot.ConfigAuthLimitCache/Middleware/OcelotMiddlewareExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Ocelot.Configuration; 3 | using Ocelot.Configuration.Repository; 4 | using Ocelot.Middleware; 5 | using System; 6 | using System.Linq; 7 | using System.Collections.Generic; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using Microsoft.Extensions.DependencyInjection; 11 | using Ocelot.Configuration.Creator; 12 | using Ocelot.DependencyInjection; 13 | using Ocelot.Responses; 14 | using Ocelot.Configuration.Setter; 15 | using Ocelot.Middleware.Pipeline; 16 | using Microsoft.AspNetCore.Hosting; 17 | using Ocelot.Logging; 18 | using System.Diagnostics; 19 | using Ocelot.Configuration.File; 20 | using Microsoft.Extensions.Options; 21 | 22 | namespace Ocelot.ConfigAuthLimitCache.Middleware 23 | { 24 | /// 25 | /// yilezhu 26 | /// 2018.10.22 27 | /// 扩展IApplicationBuilder,新增use方法 28 | /// 29 | public static class OcelotMiddlewareExtensions 30 | { 31 | /// 32 | /// 扩展UseOcelot 33 | /// 34 | /// 35 | /// 36 | public static async Task UseAhphOcelot(this IApplicationBuilder builder) 37 | { 38 | await builder.UseAhphOcelot(new OcelotPipelineConfiguration()); 39 | return builder; 40 | } 41 | 42 | /// 43 | /// 重写Ocelot,带参数 44 | /// 45 | /// 46 | /// 47 | /// 48 | public static async Task UseAhphOcelot(this IApplicationBuilder builder, OcelotPipelineConfiguration pipelineConfiguration) 49 | { 50 | var configuration = await CreateConfiguration(builder); 51 | 52 | ConfigureDiagnosticListener(builder); 53 | 54 | return CreateOcelotPipeline(builder, pipelineConfiguration); 55 | } 56 | 57 | private static async Task CreateConfiguration(IApplicationBuilder builder) 58 | { 59 | // make configuration from file system? 60 | // earlier user needed to add ocelot files in startup configuration stuff, asp.net will map it to this 61 | //var fileConfig = builder.ApplicationServices.GetService>(); 62 | var fileConfig = await builder.ApplicationServices.GetService().Get(); 63 | // now create the config 64 | var internalConfigCreator = builder.ApplicationServices.GetService(); 65 | var internalConfig = await internalConfigCreator.Create(fileConfig.Data); 66 | //Configuration error, throw error message 67 | if (internalConfig.IsError) 68 | { 69 | ThrowToStopOcelotStarting(internalConfig); 70 | } 71 | 72 | // now save it in memory 73 | var internalConfigRepo = builder.ApplicationServices.GetService(); 74 | internalConfigRepo.AddOrReplace(internalConfig.Data); 75 | 76 | //fileConfig.OnChange(async (config) => 77 | //{ 78 | // var newInternalConfig = await internalConfigCreator.Create(config); 79 | // internalConfigRepo.AddOrReplace(newInternalConfig.Data); 80 | //}); 81 | 82 | var adminPath = builder.ApplicationServices.GetService(); 83 | 84 | var configurations = builder.ApplicationServices.GetServices(); 85 | 86 | // Todo - this has just been added for consul so far...will there be an ordering problem in the future? Should refactor all config into this pattern? 87 | foreach (var configuration in configurations) 88 | { 89 | await configuration(builder); 90 | } 91 | 92 | if (AdministrationApiInUse(adminPath)) 93 | { 94 | //We have to make sure the file config is set for the ocelot.env.json and ocelot.json so that if we pull it from the 95 | //admin api it works...boy this is getting a spit spags boll. 96 | var fileConfigSetter = builder.ApplicationServices.GetService(); 97 | 98 | // await SetFileConfig(fileConfigSetter, fileConfig.Data); 99 | } 100 | 101 | return GetOcelotConfigAndReturn(internalConfigRepo); 102 | } 103 | 104 | private static bool AdministrationApiInUse(IAdministrationPath adminPath) 105 | { 106 | return adminPath != null; 107 | } 108 | 109 | //private static async Task SetFileConfig(IFileConfigurationSetter fileConfigSetter, IOptionsMonitor fileConfig) 110 | //{ 111 | // var response = await fileConfigSetter.Set(fileConfig.CurrentValue); 112 | 113 | // if (IsError(response)) 114 | // { 115 | // ThrowToStopOcelotStarting(response); 116 | // } 117 | //} 118 | 119 | private static bool IsError(Response response) 120 | { 121 | return response == null || response.IsError; 122 | } 123 | 124 | private static IInternalConfiguration GetOcelotConfigAndReturn(IInternalConfigurationRepository provider) 125 | { 126 | var ocelotConfiguration = provider.Get(); 127 | 128 | if (ocelotConfiguration?.Data == null || ocelotConfiguration.IsError) 129 | { 130 | ThrowToStopOcelotStarting(ocelotConfiguration); 131 | } 132 | 133 | return ocelotConfiguration.Data; 134 | } 135 | 136 | private static void ThrowToStopOcelotStarting(Response config) 137 | { 138 | throw new Exception($"Unable to start Ocelot, errors are: {string.Join(",", config.Errors.Select(x => x.ToString()))}"); 139 | } 140 | 141 | private static IApplicationBuilder CreateOcelotPipeline(IApplicationBuilder builder, OcelotPipelineConfiguration pipelineConfiguration) 142 | { 143 | var pipelineBuilder = new OcelotPipelineBuilder(builder.ApplicationServices); 144 | 145 | //重写自定义管道 146 | pipelineBuilder.BuildAhphOcelotPipeline(pipelineConfiguration); 147 | 148 | var firstDelegate = pipelineBuilder.Build(); 149 | 150 | /* 151 | inject first delegate into first piece of asp.net middleware..maybe not like this 152 | then because we are updating the http context in ocelot it comes out correct for 153 | rest of asp.net.. 154 | */ 155 | 156 | builder.Properties["analysis.NextMiddlewareName"] = "TransitionToOcelotMiddleware"; 157 | 158 | builder.Use(async (context, task) => 159 | { 160 | var downstreamContext = new DownstreamContext(context); 161 | await firstDelegate.Invoke(downstreamContext); 162 | }); 163 | 164 | return builder; 165 | } 166 | 167 | private static void ConfigureDiagnosticListener(IApplicationBuilder builder) 168 | { 169 | var env = builder.ApplicationServices.GetService(); 170 | var listener = builder.ApplicationServices.GetService(); 171 | var diagnosticListener = builder.ApplicationServices.GetService(); 172 | diagnosticListener.SubscribeWithAdapter(listener); 173 | } 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------