前提条件

关于Ocelot。使用NET开发微服务体系结构或为面向服务的体系结构提供统一访问系统的组件。

  • 本文将使用 Ocelot 构建统一入口的 Gateway。
  • 关于 IdentityServer4
  • IdentityServer4 是一个 OpenID Connect 和 OAuth 2.0 框架用于ASP.NET Core,IdentityServer4 在你的应用程序中集成了基于令牌认证、单点登录、api访问控制所需的所有协议和扩展点。
  • 本文将使用 IdentityServer4 搭建独立认证服务器。
  • 关于 Consul
  • Consul 是一个服务网格解决方案,通过服务发现、配置、功能分割提供一个全功能的控制层。这些功能可以单独使用,也可以同时使用以形成一个完整的网格服务。
  • 本文将使用 Consul 注册多个服务。
  • 关于 .Net Core
  • 将使用 WebApi 构建多个服务
  • 构建 IdentityServer 服务

    1.添加 ASP.Net Core Web 项目

    2.添加空项目

    3.在程序包管理控制台中输入:Install-Package Iden

    4.添加 Con 文件,并添加内容如下:

    using Sy;
    using Iden;
    using Iden;
    namespace IdentityServer
    {
    public sealed class Config
    {
    public static IEnumerable<ApiResource> GetApiResources()
    {
    return new List<ApiResource>
    {
    new ApiResource("ServiceA", "ServiceA API"),
    new ApiResource("ServiceB", "ServiceB API")
    };
    }
    public static IEnumerable<Client> GetClients()
    {
    return new List<Client>
    {
    new Client
    {
    ClientId = "ServiceAClient",
    AllowedGrantTypes = Gran,
    ClientSecrets =
    {
    new Secret("ServiceAClient".Sha256())
    },
    AllowedScopes = new List<string> {"ServiceA"},
    AccessTokenLifetime = 60 * 60 * 1
    },
    new Client
    {
    ClientId = "ServiceBClient",
    AllowedGrantTypes = Gran,
    ClientSecrets =
    {
    new Secret("ServiceBClient".Sha256())
    },
    AllowedScopes = new List<string> {"ServiceB"},
    AccessTokenLifetime = 60 * 60 * 1
    }
    };
    }
    public static List<TestUser> GetUsers()
    {
    return new List<TestUser>
    {
    new TestUser
    {
    Username = "test",
    Password = "123456",
    SubjectId = "1"
    }
    };
    }
    public static IEnumerable<IdentityResource> GetIdentityResources()
    {
    return new List<IdentityResource>();
    }
    }
    }

    注意:这里添加了两个 Client ,分别为 ServiceA、ServiceB ,因此接下来将构建这两个服务。

    5.删掉S文件,在Program.cs中添加内容如下:

    using Micro;
    using Micro.Builder;
    using Micro.Hosting;
    using Micro.Mvc;
    using Micro;
    namespace IdentityServer
    {
    public class Program
    {
    public static void Main(string[] args)
    {
    CreateWebHostBuilder(args).Build().Run();
    }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
    return WebHo(args).Configureservices(services =>
    {
    ().SetCompatibilityVersion);
    ()
    .AddDeveloperSigningCredential()
    .AddInMemoryIdentityResource())
    .AddInMemoryApiResource())
    .AddInMemoryClien())
    .AddTestUser());
    }).Configure(app =>
    {
    a();
    });
    }
    }
    }

    注意:AddDeveloperSigningCredential() 方法用于添加开发时使用的Key material生产环境中不要使用该方法。在 .NET Core 2.2 中新建的 Web 项目文件 csproj 中包含了如下内容:

    csharp <PropertyGroup> <TargetFramework>ne;/TargetFramework> <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> </PropertyGroup>

    这里更改

    csharp <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>

    为或直接删除该行,这么做的原因是当值为 InProcess 时,读写 将产生权限问题。

    csharp <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>

    6.F5 启动该服务,显示如下:

    在浏览器中输入 ,得到以下内容

    至此,一个包含两个服务认证的认证服务搭建完毕。

    构建 ServiceA、ServiceB

    1.添加 ASP.Net Core Web 项目,这里以 ServiceA 为例进行构建

    2.添加 ASP.Net Core API

    3.在 S 中添加内容如下:

    using Micro.Builder;
    using Micro.Hosting;
    using Micro.Mvc;
    using Micro;
    using Micro;
    namespace ServiceA
    {
    public class Startup
    {
    public Startup(IConfiguration configuration)
    {
    Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
    ().SetCompatibilityVersion);
    ("Bearer")
    .AddJwtBearer("Bearer", options =>
    {
    o = "http://127.0.0.1:8021";
    o = false;
    o = "ServiceA";
    });
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    if ())
    {
    a();
    }
    a();
    a();
    }
    }
    }

    4.添加 Sessioncontroller 用于用户登录,内容如下:

    using Sy;
    using Sy;
    using Sy;
    using Iden;
    using Micro.Mvc;
    namespace ServiceA.Controllers
    {
    [Route("api/[controller]")]
    [ApiController]
    public class SessionController : ControllerBase
    {
    public async Task<string> Login(UserRequestModel userRequestModel)
    {
    // discover endpoints from metadata
    var client = new HttpClient();
    DiscoveryResponse disco = await client.GetDiscoveryDocumentAsync("http://127.0.0.1:8021");
    if )
    {
    return "认证服务器未启动";
    }
    TokenResponse tokenResponse = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
    {
    Address = di,
    ClientId = "ServiceAClient",
    ClientSecret = "ServiceAClient",
    UserName = u,
    Password = u
    });
    return ? : ;
    }
    }
    public class UserRequestModel
    {
    [Required(ErrorMessage = "用户名称不可以为空")]
    public string Name { get; set; }
    [Required(ErrorMessage = "用户密码不可以为空")]
    public string Password { get; set; }
    }
    }

    5.添加 HealthController 用于 Consul 进行服务健康检查,内容如下:

    using Micro.Mvc;
    namespace ServiceA.Controllers
    {
    [Route("api/[controller]"), ApiController]
    public class HealthController : ControllerBase
    {
    /// <summary>
    /// 健康检查
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public IActionResult Get()
    {
    return Ok();
    }
    }
    }

    6.更改 Value 内容如下:

    using Sy;
    using Micro.Authorization;
    using Micro.Mvc;
    namespace ServiceA.Controllers
    {
    [Authorize] //添加 Authorize Attribute 以使该控制器启用认证
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
    return new[] { "value1", "value2" };
    }
    }
    }

    注意,以上基本完成了 ServiceA 的服务构建,但在实际应用中应做一些修改,例如:IdentityServer 地址应在 a 中进行配置,不应把地址分散于项目中各处;认证服务启用最好在全局启用,以防止漏写等等。ServiceB 的内容与 ServiceA 大致相似,因此文章中将不再展示 ServiceB 的构建过程。

    Gateway 构建

    1.添加ASP.Net Web

    2.添加空项目

    3.打开程序包管理器控制台输入命令:

    csharp install-package Ocelot //添加 Ocelot
    csharp install-package Ocelot.Provider.Consul // 添加 Consul 服务发现

    4.添加 ocelot.json 文件,内容如下

    {
    "ReRoutes": [
    {
    "DownstreamPathTemplate": "/api/{everything}",
    "DownstreamScheme": "http",
    "UpstreamPathTemplate": "/ServiceA/{everything}",
    "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
    "ServiceName": "ServiceA", //consul 服务中 ServiceA 的名称
    "LoadBalancerOptions": {
    "Type": "LeastConnection"
    }
    },
    {
    "DownstreamPathTemplate": "/api/{everything}",
    "DownstreamScheme": "http",
    "UpstreamPathTemplate": "/ServiceB/{everything}",
    "UpstreamHttpMethod": [ "GET", "POST", "DELETE", "PUT" ],
    "ServiceName": "ServiceB", //consul 服务中 ServiceB 的名称
    "LoadBalancerOptions": {
    "Type": "LeastConnection"
    }
    }
    ],
    "GlobalConfiguration": {
    "ServiceDiscoveryProvider": { // Consul 服务发现配置
    "Host": "localhost", // Consul 地址
    "Port": 8500,
    "Type": "Consul"
    }
    }
    }

    5.删除 S 文件,在 Program.cs 文件中添加如下内容

    using Sy;
    using Micro.Hosting;
    using Micro;
    using Ocelot.DependencyInjection;
    using Ocelot.Middleware;
    using Ocelot.Provider.Consul;
    namespace ApiGateway
    {
    public class Program
    {
    public static void Main(string[] args)
    {
    new WebHostBuilder()
    .UseKestrel()
    .UseContentRoo())
    .ConfigureAppConfiguration((hostingContext, config) =>
    {
    config
    .SetBasePa)
    .AddJsonFile("a", true, true)
    .AddJsonFile($"appsettings.{}.json", true, true)
    .AddJsonFile("ocelot.json")
    .AddEnvironmentVariables();
    })
    .ConfigureServices(services =>
    {
    ().AddConsul();
    })
    .ConfigureLogging((hostingContext, logging) =>
    {
    //add your logging
    })
    .UseIISIntegration()
    .Configure(app =>
    {
    a().Wait();
    })
    .Build()
    .Run();
    }
    }
    }

    注意:打开 Ga 文件,更改

    <PropertyGroup>
    <TargetFramework>ne;/TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
    </PropertyGroup>

    <PropertyGroup>
    <TargetFramework>ne;/TargetFramework>
    <AspNetCoreHostingModel>OutOfProcess</AspNetCoreHostingModel>
    </PropertyGroup>

    至此,一个基础网关基本构建完成。

    构建Consul服务

    1.使用Chocoletey安装 Consul,

    choco install consul

    2.新建一个文件夹以保存 Consul 服务配置

    3.在 con 文件夹中添加配置文件,内容如下:

    {
    "services": [{
    "ID": "ServiceA",
    "Name": "ServiceA",
    "Tags": [
    "ServiceAWebApi", "Api"
    ],
    "Address": "127.0.0.1",
    "Port": 8010,
    "Check": {
    "HTTP": ";,
    "Interval": "10s"
    }
    }, {
    "id": "ServiceB",
    "name": "ServiceB",
    "tags": [
    "ServiceBWebApi","Api"
    ],
    "Address": "127.0.0.1",
    "Port": 8011,
    "Check": [{
    "HTTP": ";,
    "Interval": "10s"
    }
    ]
    }
    ]
    }

    4.启动 consul 服务

    consul agent -dev -config-dir=./con

    启动后在浏览器中输入 以查看Consul服务

    Postman 验证

    1.F5 启动 Gateway 项目,启动 Postman 发送请求到 ServiceA 获取 Token。

    2.使用 Token 请求 ServiceA Values 接口

    3.当尝试使用 ServiceA 获取到的 Token 去获取 ServiceB 的数据时,请求也如意料之中返回 401

    总结

    至此,一个由 .NET Core、IdentityServer4、Ocelot、Consul实现的基础架构搭建完毕。

    1.《关于cs config我想说.NET Core + Ocelot + IdentityServer4 + Consul 基础架构实现》援引自互联网,旨在传递更多网络信息知识,仅代表作者本人观点,与本网站无关,侵删请联系页脚下方联系方式。

    2.《关于cs config我想说.NET Core + Ocelot + IdentityServer4 + Consul 基础架构实现》仅供读者参考,本网站未对该内容进行证实,对其原创性、真实性、完整性、及时性不作任何保证。

    3.文章转载时请保留本站内容来源地址,https://www.cxvn.com/gl/djyxgl/173142.html