一、搭建一个ID4.IdServer(.NetCore API)认证服务器项目
1.1、在该项目中添加Nuget包(vs2.1版本安装IdentityServer4 2.5.3版本)
1.2、在ID4.IdServer项目中新建一个Config类
public class Config
{
/// <summary>
/// 返回应用列表
/// </summary>
/// <returns></returns>
public static IEnumerable<ApiResource> GetApiResources()
{
List<ApiResource> resources = new List<ApiResource>();
//ApiResource第一个参数是应用的名字,第二个参数是描述
resources.Add(new ApiResource("MsgAPI", "消息服务API"));
resources.Add(new ApiResource("ProductAPI", "产品API"));
return resources;
}
/// <summary>
/// 返回账号列表
/// </summary>
/// <returns></returns>
public static IEnumerable<Client> GetClients()
{
List<Client> clients = new List<Client>();
clients.Add(new Client
{
ClientId = "clientPC1",//API账号、客户端Id
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("123321".Sha256())//秘钥
},
AllowedScopes = { "MsgAPI", "ProductAPI" }//这个账号支持访问哪些应用
});
return clients;
}
}
1.3、在ID4.IdServer项目下Startup类中ConfigureServices方法进行注册
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
//注册服务
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
}
1.4、在ID4.IdServer项目下Startup类中Configure方法进行注册中间件
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
//注册中间件
app.UseIdentityServer();
app.UseHttpsRedirection();
app.UseMvc();
}
1.5、然后在 5000 端口启动 、在 postman 里发出请求,获取 token
http://localhost:5000/connect/token,发 Post 请求,表单请求内容(注意不是报文头):
client_id=clientPC1 client_secret=123321 grant_type=client_credentials
二、 搭建 Ocelot 服务器项目
2.1、先在之前博客上OcelotTest API网关项目中添加Nuget包(vs2.1版本安装IdentityServer4 2.5.3版本)
2.2、在OcelotTest API网关项目configuration.json文件中进行修改
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/MsgService/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"ServiceName": "MsgService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"UseServiceDiscovery": true,
"AuthenticationOptions": {
"AuthenticationProviderKey": "MsgKey",
"AllowedScopes": []
}
},
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/ProductService/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"ServiceName": "ProductService",
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"UseServiceDiscovery": true,
"AuthenticationOptions": {
"AuthenticationProviderKey": "ProductKey",
"AllowedScopes": []
}
}
],
"GlobalConfiguration": {
"ServiceDiscoveryProvider": {
"Host": "loc