概述

Ocelot是一个用.NET Core实现的开源API网关技术。IdentityServer4是一个基于OpenID Connect和OAuth2.0的针对ASP.NET Core的框架,以中间件的形式存在。OAuth是一种授权机制。系统产生一个短期的token,用来代替密码,供第三方应用使用。

下面来看下如何实现Ocelot基于IdentityServer4统一认证。

主要代码实现

1、新建认证项目,nuget安装id4

2、appsettings.json 配置

{"Logging": {"LogLevel": {"Default": "Warning"}},"SSOConfig": {"ApiResources": [{"Name": "testapi","DisplayName": "testapiname"}],"Clients": [{"ClientId": "a","ClientSecrets": [ "aa" ],"AllowedGrantTypes": "ClientCredentials","AllowedScopes": [ "testapi" ]}]},"AllowedHosts": "*"
}
   public static IEnumerable<ApiResource> GetApiResources(IConfigurationSection p){List<ApiResource> resource = new List<ApiResource>();if (p != null){List<ApiConfig> configs = new List<ApiConfig>();p.Bind("ApiResources", configs);foreach (var config in configs){resource.Add(new ApiResource(config.Name, config.DisplayName));}}return resource.ToArray();}/// <summary>/// 定义受信任的客户端 Client/// </summary>/// <returns></returns>public static IEnumerable<Client> GetClients(IConfigurationSection p){List<Client> clients = new List<Client>();if (p != null){List<ClientConfig> configs = new List<ClientConfig>();p.Bind("Clients", configs);foreach (var config in configs){Client client = new Client();client.ClientId = config.ClientId;List<Secret> clientSecrets = new List<Secret>();foreach (var secret in config.ClientSecrets){clientSecrets.Add(new Secret(secret.Sha256()));}client.ClientSecrets = clientSecrets.ToArray();GrantTypes grantTypes = new GrantTypes();var allowedGrantTypes = grantTypes.GetType().GetProperty(config.AllowedGrantTypes);client.AllowedGrantTypes = allowedGrantTypes == null ?GrantTypes.ClientCredentials : (ICollection<string>)allowedGrantTypes.GetValue(grantTypes, null);client.AllowedScopes = config.AllowedScopes.ToArray();clients.Add(client);}}return clients.ToArray();}

3、Startup 配置

   public void ConfigureServices(IServiceCollection services){var p = Configuration.GetSection("SSOConfig");services.AddIdentityServer().AddDeveloperSigningCredential().AddInMemoryApiResources(SSOConfig.GetApiResources(p)).AddInMemoryClients(SSOConfig.GetClients(p));services.AddControllers().SetCompatibilityVersion(CompatibilityVersion.Latest);}// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IWebHostEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}app.UseRouting();//  app.UseAuthorization();app.UseIdentityServer();app.UseEndpoints(endpoints =>{endpoints.MapControllers();});}

4、网关项目配置

 <ItemGroup><PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /><PackageReference Include="Ocelot" Version="14.0.3" /></ItemGroup>
  {"DownstreamPathTemplate": "/connect/token","DownstreamScheme": "http","DownstreamHostAndPorts": [{"Host": "localhost","Port": 5002}],"UpstreamPathTemplate": "/token","UpstreamHttpMethod": [ "Post" ],"Priority": 2},
   var identityBuilder = services.AddAuthentication();IdentityServerConfig identityServerConfig = new IdentityServerConfig();Configuration.Bind("IdentityServerConfig", identityServerConfig);if (identityServerConfig != null && identityServerConfig.Resources != null){foreach (var resource in identityServerConfig.Resources){identityBuilder.AddIdentityServerAuthentication(resource.Key, options =>{options.Authority = $"http://{identityServerConfig.IP}:{identityServerConfig.Port}";options.RequireHttpsMetadata = false;options.ApiName = resource.Name;options.SupportedTokens = SupportedTokens.Both;});}}//  services.AddControllers();services.AddOcelot(Configuration);

测试

1、没有添加token访问,返回401

2、获取访问的token

3、带上token访问接口

一日一技:Ocelot网关使用IdentityServer4认证相关推荐

  1. 一日一技:在Ocelot网关中实现IdentityServer4密码模式(password)

    概述 IdentityServer4 是为ASP.NET Core 2.系列量身打造的一款基于 OpenID Connect 和 OAuth 2.0 认证框架.将identityserver部署在你的 ...

  2. Angular SPA基于Ocelot API网关与IdentityServer4的身份认证与授权

    在上一讲中,我们已经完成了一个完整的案例,在这个案例中,我们可以通过Angular单页面应用(SPA)进行登录,然后通过后端的Ocelot API网关整合IdentityServer4完成身份认证.在 ...

  3. Angular SPA基于Ocelot API网关与IdentityServer4的身份认证与授权(三)

    在前面两篇文章中,我介绍了基于IdentityServer4的一个Identity Service的实现,并且实现了一个Weather API和基于Ocelot的API网关,然后实现了通过Ocelot ...

  4. Angular SPA基于Ocelot API网关与IdentityServer4的身份认证与授权(二)

    上文已经介绍了Identity Service的实现过程.今天我们继续,实现一个简单的Weather API和一个基于Ocelot的API网关. 回顾 <Angular SPA基于Ocelot ...

  5. Angular SPA基于Ocelot API网关与IdentityServer4的身份认证与授权(一)

    好吧,这个题目我也想了很久,不知道如何用最简单的几个字来概括这篇文章,原本打算取名<Angular单页面应用基于Ocelot API网关与IdentityServer4+ASP.NET Iden ...

  6. .Net Core使用Ocelot网关(二) -鉴权认证

    前言 上一章.Net Core使用Ocelot网关(一) -负载,限流,熔断,Header转换 已经简单的介绍了ocelot的使用了,但是网关暴露的接口如果什么人都能访问的话安全性就太低啦.所以我们需 ...

  7. 【实战 Ids4】║ 控制台密码模式搭配Ocelot网关

    (此岁只能云赏樱了) 书接上文,这些天一直在研究IdentityServer4(下文简称Ids4)框架,发现有很多有意思,或者说比我想象中的知识点,可扩展的多,所以比较开心能钻研进去,就像当时学习AS ...

  8. mongo 改字段名_一日一技:修改MongoDB集合中的字段名

    一日一技:修改MongoDB集合中的字段名 一日一技是一个每天更新的栏目,旨在使用3分钟的时间让你每天都有新的进步. 在我们使用MongoDB的过程中,经常会出现修改数据的情况.我们一般使用 upda ...

  9. python线程监控配置文件_一日一技:Python多线程的事件监控

    一日一技:Python多线程的事件监控 设想这样一个场景: 你创建了10个子线程,每个子线程分别爬一个网站,一开始所有子线程都是阻塞等待.一旦某个事件发生:例如有人在网页上点了一个按钮,或者某人在命令 ...

最新文章

  1. C/C++实现如下 根据Merge Sort原理, 自己实现的归并排序算法+详细注释+代码(C#,C/C++)...
  2. Leetcode 25 K个一组翻转链表 (每日一题 20210719)
  3. android 设置PopupWindow的显示大小
  4. “Hello,Github!——如何配置并上传一个已有项目到Git上
  5. 做安全操作系统,这位技术老兵是认真的!
  6. 十六、定义数据、定义栈
  7. Laravel 支付宝SDK在Laravel5的封装
  8. wegwegwegwegweg
  9. Mysql导入导出数据总结
  10. [码海拾贝 之TC] 使用View 定义动态的Class
  11. ubuntu18 mysql5.6源码_Ubuntu 18.04 使用Systemd管理MySQL 5.6
  12. HttpClient 解释
  13. 去除暴风影音2009广告的方法!
  14. 面试题java的权限_Java shiro面试题
  15. 计算机无法用u盘重装系统,最简单不用U盘电脑重装系统教程
  16. macOS上如何通过.crash文件定位崩溃地址
  17. 一文详解PPTC自恢复保险丝的设计应用
  18. 大数据加工的方法,主要分为哪几种?
  19. JAVA SE 基础汇总
  20. 什么缩写是mzj_mzjh是什么意思,mzjh缩写代表什么意思,mzjh是什么含义

热门文章

  1. python中o_Python I/O与进程的详细讲解
  2. js 下拉底部加载|滑轮滚动到页面底部ajax加载数据的实例
  3. 基于.NET2.0的System.Net.Mail发送邮件Demo
  4. LeetCode 最大正方形
  5. oracle 基本异常的练习及各个错误码
  6. Ubuntu16.04 + caffe-ssd + [CPU_ONLY] + KITTI 训练总结
  7. Msys2 国内源(2017.3.30)
  8. HQ-day2 C#语言基础
  9. 指针04 - 零基础入门学习C语言44
  10. 百度地图精确定位html,HTML5地理定位,百度地图API,知识点熟悉