• 微服务Ocelot基础配置


    微服务-Ocelot基础配置

    前言:如果还不了解网关的,可以去看下我之前的介绍,本文将介绍一下如何配置网关里面对应的swagger以及网关对应的跨域问题,以及Jwt配置,下面直接进入主题:

    一、配置Jwt,实现步骤如下:首先添加JetBearer包

    1. 添加JWT配置文件,下面有用到

    {
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft.AspNetCore": "Warning"
        }
      },
      "AllowedHosts": "*",
      "JWTTokenOptions": {  //添加jwt配置文件
        "Audience": "http://localhost:5726",
        "Issuer": "http://localhost:5726",
        "SecurityKey": "MIGfMA0GCSqGSIb3DQ"
      }
    }

    2. 修改Program.cs类里面的方法:

    备注:以往我们需要添加鉴权中间件,但是此处不能添加,会报错:中间件(app.UseAuthentication)

    修改如下:

    #region jwt校验  HS
    JWTTokenOptions tokenOptions = new JWTTokenOptions();
    builder.Configuration.Bind("JWTTokenOptions", tokenOptions);
    string authenticationProviderKey = "UserGatewayKey";
    
    builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)//Bearer Scheme
    .AddJwtBearer(authenticationProviderKey, options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            //JWT有一些默认的属性,就是给鉴权时就可以筛选了
            ValidateIssuer = true,//是否验证Issuer
            ValidateAudience = true,//是否验证Audience
            ValidateLifetime = true,//是否验证失效时间---默认还添加了300s后才过期
            ClockSkew = TimeSpan.FromSeconds(0),//token过期后立马过期
            ValidateIssuerSigningKey = true,//是否验证SecurityKey
    
            ValidAudience = tokenOptions.Audience,//Audience,需要跟前面签发jwt的设置一致
            ValidIssuer = tokenOptions.Issuer,//Issuer,这两项和前面签发jwt的设置一致
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenOptions.SecurityKey)),//拿到SecurityKey
        };
    });
    #endregion

    3. 

    //*****************************超时+限流+熔断+降级+Consul+Polly********************************
    {
      "Routes": [
        {
          "DownstreamPathTemplate": "/api/{url}", //服务地址--url变量
          "DownstreamScheme": "http",
          "UpstreamPathTemplate": "/T/{url}", //网关地址--url变量
          "UpstreamHttpMethod": [ "Get", "Post" ],
          "UseServiceDiscovery": true,
          "ServiceName": "UserWebAPIService", //consul服务名称
          "LoadBalancerOptions": {
            "Type": "RoundRobin" //轮询      LeastConnection-最少连接数的服务器   NoLoadBalance不负载均衡
          },
          "RateLimitOptions": {
            "ClientWhitelist": [ "eleven", "seven" ], //白名单 ClientId 区分大小写
            "EnableRateLimiting": true,
            "Period": "5m", //1s, 5m, 1h, 1d
            "PeriodTimespan": 30, //多少秒之后客户端可以重试
            "Limit": 5 //统计时间段内允许的最大请求数量
          },
          "AuthenticationOptions": {
            "AuthenticationProviderKey": "UserGatewayKey", //UserGatewayKey 这个是我上面有用到的
            "AllowedScopes": [ "UserWebAPIService", "UserMinimalAPIService" ]
          },
          "RouteClaimsRequirement": {
            "Role": "Assistant"
          },
          "QoSOptions": {
            "ExceptionsAllowedBeforeBreaking": 3, //允许多少个异常请求
            "DurationOfBreak": 10000, // 熔断的时间,单位为ms
            "TimeoutValue": 2000 //单位ms 如果下游请求的处理时间超过多少则自如将请求设置为超时 默认90秒
          },
          "FileCacheOptions": {
            "TtlSeconds": 15,
            "Region": "UserCache" //可以调用Api清理
          }
        }
      ],
      "GlobalConfiguration": {
        "BaseUrl": "http://127.0.0.1:6299", //网关对外地址
        "ServiceDiscoveryProvider": {
          "Host": "127.0.0.1",
          "Port": 8500,
          "Type": "Consul" //由Consul提供服务发现
        },
        "RateLimitOptions": {
          "QuotaExceededMessage": "Too many requests, maybe later? 11", // 当请求过载被截断时返回的消息
          "HttpStatusCode": 666, // 当请求过载被截断时返回的http status
          "ClientIdHeader": "client_id" // 用来识别客户端的请求头,默认是 ClientId
        }
      }
    }

    一、配置网关里面对应的swagger

    //*****************************服务器配置swagger********************************
    {
      "Routes": [
        {
          "DownstreamPathTemplate": "/api/{url}", //服务地址--url变量
          "DownstreamScheme": "http",
          "DownstreamHostAndPorts": [
            {
              "Host": "192.168.3.230",
              "Port": 5030 //服务端口
            }
          ],
          "UpstreamPathTemplate": "/T5030/{url}", //网关地址--url变量
          "UpstreamHttpMethod": [ "Get", "Post" ]
        },
        {
          "UpstreamPathTemplate": "/webapi/swagger/v1/swagger.json",
          "UpstreamHttpMethod": [ "Get" ],
          "DownstreamHostAndPorts": [
            {
              "Host": "192.168.3.230",
              "Port": 5030 //服务端口
            }
          ],
          "DownstreamPathTemplate": "/swagger/v1/swagger.json",
          "DownstreamScheme": "http"
        },
        {
          "UpstreamPathTemplate": "/webapiV2/swagger/v2/swagger.json",
          "UpstreamHttpMethod": [ "Get" ],
          "DownstreamHostAndPorts": [
            {
              "Host": "192.168.3.230",
              "Port": 5030 //服务端口
            }
          ],
          "DownstreamPathTemplate": "/swagger/v1/swagger.json",
          "DownstreamScheme": "http"
        }
      ]
    }

    二、网关对应的跨域

    ////*****************************单地址+跨域********************************
    //{
    //  "Routes": [
    //    {
    //      "DownstreamPathTemplate": "/api/{url}", //服务地址--url变量
    //      "DownstreamScheme": "http",
    //      "DownstreamHeaderTransform": {
    //        "Access-Control-Allow-Origin": "http://localhost:8070", //不存在就添加
    //        "Access-Control-Allow-Methods": "*",
    //        "Access-Control-Allow-Headers": "*"
    //      },
    //      "DownstreamHostAndPorts": [
    //        {
    //          "Host": "192.168.3.230",
    //          "Port": 5030 //服务端口
    //        }
    //      ],
    //      "UpstreamPathTemplate": "/T5030/{url}", //网关地址--url变量
    //      "UpstreamHttpMethod": [ "Get", "Post", "Put", "PATCH", "Delete", "Options" ]
    //    }
    //  ]
    //}

    谢谢学习!!!共同进步,如有疑问,请留言~

  • 相关阅读:
    C语言第五次作业
    C语言第四次作业
    C语言第三次作业

    第一次作业
    C语言第五次作业
    C语言第四次作业
    C语言第三次作业
    C语言理论作业—2
    燕勇鹏-160809318
  • 原文地址:https://www.cnblogs.com/wangjinya/p/15877228.html
Copyright © 2020-2023  润新知