聊聊Ocelot网关使用IdentityServer4认证

网络 通信技术
Ocelot是一个用.NET Core实现的开源API网关技术。IdentityServer4是一个基于OpenID Connect和OAuth2.0的针对ASP.NET Core的框架,以中间件的形式存在。

 [[387801]]

本文转载自微信公众号「UP技术控」,作者conan5566 。转载本文请联系UP技术控公众号。 

概述

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

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

主要代码实现

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

2、appsettings.json 配置

  1.   "Logging": { 
  2.     "LogLevel": { 
  3.       "Default""Warning" 
  4.     } 
  5.   }, 
  6.   "SSOConfig": { 
  7.     "ApiResources": [ 
  8.       { 
  9.         "Name""testapi"
  10.         "DisplayName""testapiname" 
  11.       } 
  12.     ], 
  13.     "Clients": [ 
  14.       { 
  15.         "ClientId""a"
  16.         "ClientSecrets": [ "aa" ], 
  17.         "AllowedGrantTypes""ClientCredentials"
  18.         "AllowedScopes": [ "testapi" ] 
  19.       } 
  20.     ] 
  21.   }, 
  22.   "AllowedHosts""*" 
  1. public static IEnumerable<ApiResource> GetApiResources(IConfigurationSection section
  2.         { 
  3.             List<ApiResource> resource = new List<ApiResource>(); 
  4.             if (section != null
  5.             { 
  6.                 List<ApiConfig> configs = new List<ApiConfig>(); 
  7.                 section.Bind("ApiResources", configs); 
  8.                 foreach (var config in configs) 
  9.                 { 
  10.                     resource.Add(new ApiResource(config.Name, config.DisplayName)); 
  11.                 } 
  12.             } 
  13.             return resource.ToArray(); 
  14.         } 
  15.  
  16.         /// <summary> 
  17.         /// 定义受信任的客户端 Client 
  18.         /// </summary> 
  19.         /// <returns></returns
  20.         public static IEnumerable<Client> GetClients(IConfigurationSection section
  21.         { 
  22.             List<Client> clients = new List<Client>(); 
  23.             if (section != null
  24.             { 
  25.                 List<ClientConfig> configs = new List<ClientConfig>(); 
  26.                 section.Bind("Clients", configs); 
  27.                 foreach (var config in configs) 
  28.                 { 
  29.                     Client client = new Client(); 
  30.                     client.ClientId = config.ClientId; 
  31.                     List<Secret> clientSecrets = new List<Secret>(); 
  32.                     foreach (var secret in config.ClientSecrets) 
  33.                     { 
  34.                         clientSecrets.Add(new Secret(secret.Sha256())); 
  35.                     } 
  36.                     client.ClientSecrets = clientSecrets.ToArray(); 
  37.                     GrantTypes grantTypes = new GrantTypes(); 
  38.                     var allowedGrantTypes = grantTypes.GetType().GetProperty(config.AllowedGrantTypes); 
  39.                     client.AllowedGrantTypes = allowedGrantTypes == null ? 
  40.  GrantTypes.ClientCredentials : (ICollection<string>)allowedGrantTypes.GetValue(grantTypes, null); 
  41.                     client.AllowedScopes = config.AllowedScopes.ToArray(); 
  42.                     clients.Add(client); 
  43.                 } 
  44.             } 
  45.             return clients.ToArray(); 
  46.         } 

3、Startup 配置

  1. public void ConfigureServices(IServiceCollection services) 
  2.         { 
  3.             var section = Configuration.GetSection("SSOConfig"); 
  4.             services.AddIdentityServer() 
  5.          .AddDeveloperSigningCredential() 
  6.          .AddInMemoryApiResources(SSOConfig.GetApiResources(section)) 
  7.          .AddInMemoryClients(SSOConfig.GetClients(section)); 
  8.             services.AddControllers().SetCompatibilityVersion(CompatibilityVersion.Latest); 
  9.         } 
  10.  
  11.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
  12.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 
  13.         { 
  14.             if (env.IsDevelopment()) 
  15.             { 
  16.                 app.UseDeveloperExceptionPage(); 
  17.             } 
  18.  
  19.             app.UseRouting(); 
  20.  
  21.             //  app.UseAuthorization(); 
  22.             app.UseIdentityServer(); 
  23.  
  24.             app.UseEndpoints(endpoints => 
  25.             { 
  26.                 endpoints.MapControllers(); 
  27.             }); 
  28.         } 

4、网关项目配置

  1. <ItemGroup> 
  2.     <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" /> 
  3.     <PackageReference Include="Ocelot" Version="14.0.3" /> 
  4.   </ItemGroup> 
  1.       "DownstreamPathTemplate""/connect/token"
  2.       "DownstreamScheme""http"
  3.       "DownstreamHostAndPorts": [ 
  4.         { 
  5.           "Host""localhost"
  6.           "Port": 5002 
  7.         } 
  8.       ], 
  9.       "UpstreamPathTemplate""/token"
  10.       "UpstreamHttpMethod": [ "Post" ], 
  11.       "Priority": 2 
  12.     }, 
  1. var identityBuilder = services.AddAuthentication(); 
  2.             IdentityServerConfig identityServerConfig = new IdentityServerConfig(); 
  3.             Configuration.Bind("IdentityServerConfig", identityServerConfig); 
  4.             if (identityServerConfig != null && identityServerConfig.Resources != null
  5.             { 
  6.                 foreach (var resource in identityServerConfig.Resources) 
  7.                 { 
  8.                     identityBuilder.AddIdentityServerAuthentication(resource.Key, options => 
  9.                     { 
  10.                         options.Authority = $"http://{identityServerConfig.IP}:{identityServerConfig.Port}"
  11.                         options.RequireHttpsMetadata = false
  12.                         options.ApiName = resource.Name
  13.                         options.SupportedTokens = SupportedTokens.Both; 
  14.                     }); 
  15.                 } 
  16.             } 
  17.  
  18.             //  services.AddControllers(); 
  19.             services.AddOcelot(Configuration); 

测试

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

2、获取访问的token

3、带上token访问接口

 

 

责任编辑:武晓燕 来源: UP技术控
相关推荐

2021-05-12 00:12:37

Ocelot网关密码

2021-09-14 10:48:33

Ocelot网关

2022-01-19 22:14:36

Apache APIAPI 网关插件

2021-03-12 00:04:52

网关Api

2021-01-14 10:00:57

Restful接口

2020-07-07 07:54:01

API网关微服务

2010-04-12 13:45:35

Oracle认证

2016-10-18 11:28:21

2021-06-07 08:04:39

Restorecon命令安全

2022-02-22 08:00:48

JavaNIOBuffer

2023-03-01 08:57:32

2024-07-31 09:09:20

2024-05-28 08:24:18

2023-11-20 07:19:33

2020-04-23 18:24:40

戴尔

2024-03-06 11:38:12

Appwrite方式Supabase

2021-11-29 10:24:56

WasmEnvoy 负载均衡

2021-02-07 23:58:10

单例模式对象

2010-08-19 14:41:22

静态路由

2024-04-10 10:11:14

蓝牙蓝牙网关
点赞
收藏

51CTO技术栈公众号