.Net Core使用Ocelot网关(二) -鉴权认证
前言
上一章已经简单的介绍了ocelot的使用了,但是网关暴露的接口如果什么人都能访问的话安全性就太低啦。所以我们需要去鉴权和认证。这里我们使用identityServer4给我们的网关来鉴权认证。
创建Identity服务
我们创建一个identity的服务来用于令牌的发放和鉴权。下图是我的项目结构。
Api_Gatewat端口:5000
Api_A端口:5001
Api_B端口:5002
IdentityServer端口:5003
通过nuget添加IdentityServer4的包,也可以通过程序包管理控制台执行以下命令Install-Package IdentityServer4
。
添加一个Congif文件。
using System.Collections.Generic; using IdentityModel; using IdentityServer4; using IdentityServer4.Models; namespace IdentityServer { public static class Config { public static IEnumerable<IdentityResource> GetIdentityResourceResources() { return new List<IdentityResource> { new IdentityResources.OpenId(), //必须要添加,否则报无效的scope错误 }; } // scopes define the API resources in your system public static IEnumerable<ApiResource> GetApiResources() { //可访问的API资源(资源名,资源描述) return new List<ApiResource> { new ApiResource("Api_A", "Api_A"), new ApiResource("Api_B", "Api_B") }; } public static IEnumerable<Client> GetClients() { return new List<Client> { new Client { ClientId = "client_a", //访问客户端Id,必须唯一 //使用客户端授权模式,客户端只需要clientid和secrets就可以访问对应的api资源。 AllowedGrantTypes = GrantTypes.ClientCredentials, ClientSecrets = { new Secret("secret".Sha256()) }, AllowedScopes = { "Api_A",IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile } }, new Client { ClientId = "client_b", ClientSecrets = new [] { new Secret("secret".Sha256()) }, AllowedGrantTypes = GrantTypes.ClientCredentials, AllowedScopes = { "Api_B",IdentityServerConstants.StandardScopes.OpenId,IdentityServerConstants.StandardScopes.Profile } } }; } } }
添加两个API资源,并且添加两个客户端分别去访问不同资源。
在 Startup
中的 ConfigureServices
中配置IdentityServer服务。
public void ConfigureServices(IServiceCollection services) { services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(Config.GetApiResources()) .AddInMemoryClients(Config.GetClients()); }
在 Configure
中把IdentityServer放入http管道中。
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseIdentityServer(); }
为ocelot集成Identity