ocelot其它部分

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

权限认证

目前基本解决了结构问题。官网还提供了认证集成。

官网文档身份验证 — Ocelot 1.0.0 文档

目前网上有很多介绍集成IdentityServer4,已经很成熟。

介绍几篇博客

Consul+Ocelot搭建微服务实践--IdentityServer集成_Jonny Lin的博客-CSDN博客

Ocelot简易教程五之集成IdentityServer认证以及授权 - 依乐祝 - 博客园 (cnblogs.com)

.NET Core微服务之基于Ocelot+IdentityServer实现统一验证与授权_dotNET跨平台的博客-CSDN博客

对应IdentityServer4是新版

需要在服务项目nuget Duende.IdentityServer


builder.Services.AddIdentityServer(options =>
{
    options.EmitStaticAudienceClaim = true;
})
    .AddInMemoryIdentityResources(Config.GetIdentityResources())
    .AddInMemoryApiScopes(Config.ApiScopes)
    .AddInMemoryClients(Config.GetClients());
 public class Config
    {
        public static IEnumerable<ApiResource> GetApiResources()
        {
            return new List<ApiResource>()
            {
                new ApiResource("api", "My Api"){ Scopes ={"api"} }
            };
        }

        public static IEnumerable<Client> GetClients()
        {
            return new List<Client>()
            {
                new Client()
                {
                    ClientId = "client",
                    AllowedGrantTypes = GrantTypes.ResourceOwnerPasswordAndClientCredentials,
                     AccessTokenType = AccessTokenType.Reference,
                    ClientSecrets =
                    {
                        new Secret("123456".Sha256())
                    },
                    AllowedScopes =
                    {
                        "api"
                    },
                  Claims =new List<ClientClaim>()
                  {
                   new ClientClaim(IdentityModel.JwtClaimTypes.Role,"admin"),
                    new ClientClaim(IdentityModel.JwtClaimTypes.NickName,"江北"),
                     new ClientClaim("Email","**********@163.com"),
               }
                }
            };
        }

        public static IEnumerable<ApiScope> ApiScopes =>
            new ApiScope[] { new ApiScope("api") };

        public static IEnumerable<IdentityResource> GetIdentityResources()
        {
            return new List<IdentityResource>
            {
                new IdentityResources.OpenId(),
                new IdentityResources.Profile()
            };
        }

        public static IEnumerable<TestUser> Users()
        {
            return new[]
            {
                new TestUser
                {
                    SubjectId = "",
                    Username = "mail@qq.com",
                    Password = "password"
                }
            };
        }
    }

ocelot也需要引入Duende.IdentityServer

//添加鉴权认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer("AuthKey", options =>
                {
                    //鉴权中心服务地址
                    options.Authority = "https://localhost:19138";
                    options.RequireHttpsMetadata = false;
                    options.Audience = "api";
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateAudience = false
                    };
                });

其实和IdentityServer4集成一样只是库不同。

Polly熔断

Polly是一种开源的.NET弹性和瞬态故障处理库允许我们以非常顺畅和线程安全的方式来执诸如行重试断路超时故障恢复等策略。

Polly主要功能

重试Retry

断路器Circuit-breaker

超时检测Timeout

缓存Cache

降级FallBack

在ocelot项目中引入Ocelot.Provider.Polly

添加

builder.Services.AddOcelot(builder.Configuration).AddConsul().AddPolly(); //加 Consul服务 polly

其他信息推荐一篇文章

Ocelot 学习二 Polly - CRUDEngineer - 博客园 (cnblogs.com)

我的配置

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Information",
        "System": "Information"
      }
    },
    "WriteTo": [
      { "Name": "Console" },
      {
        "Name": "File",
        "Args": { "path": "C:\\LogFiles\\log.txt" }
      }
    ],
    "Enrich": [ "FromLogContext", "WithMachineName", "WithThreadId" ]
  },
  "Routes": [
    {
      "UseServiceDiscovery": true,
      "DownstreamPathTemplate": "/api/{url}",
      "DownstreamScheme": "http",
      "ServiceName": "homepage",
      "LoadBalancerOptions": {
        "Type": "LeastConnection"
      },
      "UpstreamPathTemplate": "/ss/{url}",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      // "ReRoutesCaseSensitive": false, // non case sensitive
      //"RateLimitOptions": {
      //  "ClientWhitelist": [], //白名单
      //  "EnableRateLimiting": true,
      //  "Period": "5m",     // 1s,5m,1h,1d
      //  "PeriodTimespan": 5,//多少秒之后客户端可以重试
      //  "Limit": 5          //统计时间段内允许的最大请求数量
      //},
      //缓存
      "FileCacheOptions": {
        "TtlSeconds": 30 //缓存时间秒
      },
      "AuthenticationOptions": {

        "AuthenticationProviderKey": "AuthKey",

        "AllowedScopes": []

      }
      //熔断设置
      //"QoSOptions": {
      //  "ExceptionsAllowedBeforeBreaking": 3, //允许多少个异常请求
      //  "DurationOfBreak": 10000, // 熔断的时间,单位为ms
      //  "TimeoutValue": 10000 // 如果下游请求的处理时间超过多少则自如将请求设置为超时 默认90秒
      //}
    }
  ],
  "urls": "https://*:5000;http://*:4000",
  "GlobalConfiguration": {
    //"BaseUrl": null,
    "RequestIdKey": "OcRequestId",
    "ReRouteIsCaseSensitive": true, //是否区分路由字母大小写
    "ServiceDiscoveryProvider": {
      "Host": "localhost", // Consul Service IP
      "Port": 8500 // Consul Service Port
      // "Type": "Consul"
      //"Type": "PollConsul",
      //"PollingInterval": 100 //健康检查时间端
    },
    "RateLimitOptions": {
      "QuotaExceededMessage": "Too many requests,maybe later?11", // 当请求过载被截断时返回的消息
      "HttpStatusCode": 666 // 当请求过载被截断时返回的http status
    }

  }

}

微服务结构

目前走马观花一样说了一遍也基本就这些内容目前。

祝大家新年新气象。

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6