.net core 3.1 Ocelot 与 Identity Server4 鉴权
电脑版发表于:2020/12/11 11:54
目录与前言
目录链接:.net core Ocelot 简单网关集群熔断架构整合目录



.net core 3.1 Identity Server4 (ClientCredentials模式)
通过参考上面的连接达成 Ocelot 与 IdentityServer4 的 ClientCredentials 进行合并,实现鉴权功能
添加 AiDaSi.OcDemo.Authenzation 项目到解决方案中
1. AiDaSi.OcDemo.Authenzation 项目结构如下图所示

对 AiDaSi.OcDemo.ServiceInstance API项目添加鉴权
1.添加 IdentityServer4.AccessTokenValidation 依赖

2.修改 WeatherForecastController.cs 添加 Authorize
3.在 Startup.cs 添加鉴权
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddControllersWithViews(option =>
{
option.ReturnHttpNotAcceptable = true;
//option.EnableEndpointRouting = false;
}).AddXmlDataContractSerializerFormatters();
services
.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", config =>
{
config.Authority = "http://localhost:7200";
//确定使用哪些资源
config.Audience = "ApiOne";
config.RequireHttpsMetadata = false;
//关键
config.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuer = false,
ValidateAudience = false
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
//只执行一次
this.Configuration.ConsulRegist();
}运行测试API项目添加鉴权是否成功
启动2个项目
获取 Access Token

3.用 Access Token 尝试访问 WeatherForecast 接口
Ocelot 与 ID4 的鉴权
1. 打开 Ocelot 项目,修改配置文件
{
"ReRoutes": [
{
"UpstreamPathTemplate": "/consul/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"ServiceName": "AiDaSiService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"UseServiceDiscovery": true,
//鉴权
"AuthenticationOptions": {
"AuthenticationProviderKey": "Bearer",
"AllowedScopes": []
}
}
],
"GlobalConfiguration": {
"BaseUrl": "http://127.0.0.1:6299",
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Type": "Consul"
}
}
}2.修改 Startup.cs
public void ConfigureServices(IServiceCollection services)
{
#region Ids4
//IdentityModelEventSource.ShowPII = true;
services
.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", config =>
{
config.Authority = "http://localhost:7200";
//确定使用哪些资源
config.Audience = "ApiOne";
config.RequireHttpsMetadata = false;
//取消验证用户以及验证角色
config.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuer = false,
ValidateAudience = false
};
});
#endregion
//services.AddControllers();
services.AddOcelot()
//使用 counsulconfiguration.json 并添加 Ocelot.Provider.Consul 包
.AddConsul()
//添加缓存
.AddCacheManager(x=> {
x.WithDictionaryHandle(); //默认字典存储
})
//使用 counsulpollyconfiguration.json 并添加 Ocelot.Provider.Polly 包
.AddPolly()
;
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseOcelot();
app.UseAuthorization();
}
3.启动 Consul
.\consul.exe agent -dev
测试鉴权功能
1.启动网关,访问相关路径

