.net 微服务_.NET微服务从0到1:API网关(Ocelot)

(给DotNet加星标,提升.Net技能)

转自:江浙沪柯蓝 cnblogs.com/zhaobingwang/p/12424708.html

Ocelot

Ocelot是用.NET Core实现的一个开源API网关。包含身份验证、路由、请求聚合等功能。能够轻松的集成IdentityServer

Ocelot的五种部署方式

  • 基本使用

3ede494b58efdfb829e70a902f3fe76c.png

  • 集成IdentityServer

a194564a267a2983f01d702bc1af5e99.png

  • 多实例

37937cd741b7dd4dfc9e3b073e612040.png

  • 集成Consul

4657c2e50f576de97aa6ecf39c164713.png

  • 集成 Service Fabric

215f7a544ada58873c9e4906d5c8d118.png

开始使用

新建网关项目

新建一个Web项目ApiGateways,添加nuget包引用

Install-Package Ocelot

bd36df54287bab998d7fb2ce19546cc4.png

添加ocelot配置文件

  • ocelot.json

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/todos/{id}",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "jsonplaceholder.typicode.com",
"Port": 443
}
],
"UpstreamPathTemplate": "/todos/{id}",
"UpstreamHttpMethod": [ "Get" ]
}
],
"GlobalConfiguration": {
"BaseUrl": "https://localhost:5000"
}
}

此配置中,ReRoutes节点下的Downstream相关节点表示网关下游服务相关配置,以上,我们指定了任意请求都以https请求转发,其中DownstreamHostAndPorts表示下游服务地址和端口。Upstream表示上游请求配置

  • 配置服务引入oeclot.json

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostingContext, config) =>
{ config.SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
.AddJsonFile("ocelot.json")
.AddEnvironmentVariables();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup();
});

此配置中,我们的网关服务运行在http://localhost,其中AuthenticationOptions是认证服务相关配置,另外有一个下游服务运行在http://localhost:5201。

将Ocelot服务添加到容器服务

public void ConfigureServices(IServiceCollection services){
services.AddOcelot();
}

将Ocelot添加请求管道

public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
app.UseOcelot();
}

创建身份认证服务

新建一个Identity.API项目

添加nuget

Install-Package IdentityServer4 -Version 3.1.2

e57cef67f07bfbb66db891df2bbcfeee.png

添加IdentityServer4配置

  • IdentityServer4 配置

为便于展示,不做持久化,写在内存中

public static class Config{
// Defining an API Resource
public static IEnumerable Apis => new List
{new ApiResource("gateway_api","ApiGateways")
};// Defining Clientpublic static IEnumerable Clients => new List
{new Client
{
ClientId="app_test",// no interactive user, use the clientid/secret for authentication
AllowedGrantTypes=GrantTypes.ClientCredentials,// secret for authentication
ClientSecrets={new Secret("123456".Sha256())
},// scopes that client has access to
AllowedScopes=new List{"gateway_api",
}
}
};// Defineing Identity Resourcepublic static IEnumerable IdentityResources => new List
{new IdentityResources.OpenId(),new IdentityResources.Profile(),
};
}
  • 添加IdentityServer4到容器

public void ConfigureDevelopmentServices(IServiceCollection services){
var builder = services.AddIdentityServer()
.AddInMemoryApiResources(Config.Apis)
.AddInMemoryClients(Config.Clients)
.AddInMemoryIdentityResources(Config.IdentityResources);
builder.AddDeveloperSigningCredential();
services.AddControllers();
}
  • 添加IdentityServer4到请求管道

public void Configure(IApplicationBuilder app, IWebHostEnvironment env){
app.UseHttpsRedirection();
app.UseRouting();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}

创建一个ServiceA

4ea7869b1cd726646c19b2fe41868d63.png

我们将在ServiceA中提供一个简单服务:为一个用户打一个标签

[Route("[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpPost]
[Route("tag/create")]
public IActionResult CreateTag([FromForm]int userId, [FromForm]string value){
// 假设数据库记录添加成功,直接返回对象
Tag tagEntity = new Tag();
tagEntity.Id = 1;
tagEntity.UserId = userId;
tagEntity.Value = value;
return Ok(tagEntity);
}
}
public class Tag
{
public int Id { get; set; }
public int UserId { get; set; }
public string Value { get; set; }
}

终章

支持我们三个项目已经建立完成,但要通过网关经身份认证服务请求到创建标签的服务,我们还需要对网关服务做一些修改。

首先,在ocelot.json新增AuthenticationOptions配置IdentityServer4身份认证服务中对应的资源

{
"ReRoutes": [
{
"DownstreamPathTemplate": "/{url}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 5201
}
],
"UpstreamPathTemplate": "/service-a/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"AuthenticationOptions": {
"AuthenticationProviderKey": "SampleKey",
"AllowedScopes": [ "gateway_api" ]
}
}
],
"GlobalConfiguration": {
"BaseUrl": "http://localhost"
}
}

其中http://localhost:5201是我们ServiceA运行的地址

然后我们需要注入认证服务到容器

Install-Package IdentityServer4.AccessTokenValidation -Version 3.0.1

public void ConfigureServices(IServiceCollection services){
var authenticationProviderKey = "SampleKey";
Action options = o =>
{
o.Authority = "http://localhost:5200";
o.ApiName = "gateway_api";
o.SupportedTokens = SupportedTokens.Both;
o.ApiSecret = "123456";
o.RequireHttpsMetadata = false;
};
services.AddAuthentication() .AddIdentityServerAuthentication(authenticationProviderKey, options);
services.AddOcelot();
}

其中http://localhost:5200是我们认证服务运行的地址

  • 通过网关直接调用

cc25445c982f6eb136ae0602c17ce990.png

我们发现返回401未授权,这是正常的,因为我们为网关服务添加了认证服务。

  • 通过token访问

我们首先要去拿token,我们现在暂时先通过postman直接获取token

d6713ad2d6dbe818604002ca884bd033.png

通过token访问

0cf6c4d2b9aeadba0dbe6f4af70f32bf.png

我们可以看到已经成功请求到了创建用户标签接口

参考

Ocelot官方文档:https://ocelot.readthedocs.io/en/latest/

.NET Core开源API网关 – Ocelot中文文档:https://www.cnblogs.com/jesse2013/p/net-core-apigateway-ocelot-docs.html

推荐阅读   点击标题可跳转

一起读源码走进C#并发队列的内部世界

.NET微服务实践:微服务框架选型

.NET Core技术研究-中间件的由来和使用

看完本文有收获?请转发分享给更多人

关注「DotNet」加星标,提升.Net技能 

1860d2432faf55b591b65e4db2d10467.png

好文章,我在看❤️

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值