tnblog
首页
视频
资源
登录

.net core 3.1 Ocelot 与 Identity Server4 鉴权

6428人阅读 2020/12/11 11:54 总访问:2534767 评论:0 收藏:0 手机
分类: Ids4

目录与前言


目录链接:.net core Ocelot 简单网关集群熔断架构整合目录


Unsplashed background img 1

.net core 3.1 Identity Server4 (ClientCredentials模式)

 通过参考上面的连接达成 Ocelot 与 IdentityServer4 的 ClientCredentials 进行合并,实现鉴权功能


添加 AiDaSi.OcDemo.Authenzation 项目到解决方案中



1. AiDaSi.OcDemo.Authenzation 项目结构如下图所示



对 AiDaSi.OcDemo.ServiceInstance API项目添加鉴权


1.添加 IdentityServer4.AccessTokenValidation 依赖



nuget

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项目添加鉴权是否成功


  1. 启动2个项目

  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.启动网关,访问相关路径







欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739

评价
这一世以无限游戏为使命!
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术