consul、ocelot、identityserver结合使用
创建identityserver项目
创建新项目
dotnet new webapi --name ids4
安装IdentityServer4
dotnet add package IdentityServer4 --version 3.1.0
在startup.cs中代码修改如下
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddInMemoryClients(config.GetClients())
.AddInMemoryApiResources(config.GetApiResources());
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseHttpsRedirection();
...
在根目录创建config.cs文件
using IdentityServer4.Models;
using System.Collections.Generic;
namespace ids4
{
public static class config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new[]{new ApiResource("api1", "My API #1")};
}
public static IEnumerable<Client> GetClients()
{
return new[]
{
new Client
{
ClientId = "xing",
ClientSecrets = new[]{new Secret("secret".Sha256())},
AllowedGrantTypes = GrantTypes.ClientCredentials,
AllowedScopes = new[]{"api1"}
}
};
}
}
}
然后运行项目,用postman进行测试,可以返回token
在gateway进行权限验证
在之前gateway项目中
安装
dotnet add package IdentityServer4.AccessTokenValidation --version 3.0.1
在startup.cs文件中代码修改如下
public void ConfigureServices(IServiceCollection services)
{
string AuthenticationProviderKey = "gatewayKey";
services.AddAuthentication("Bearer")
.AddIdentityServerAuthentication(AuthenticationProviderKey,options =>
{
options.Authority = "http://localhost:5000";
options.ApiName = "api1";
options.RequireHttpsMetadata = false;
options.SupportedTokens = SupportedTokens.Both;
});
services.AddOcelot()
.AddConsul()
.AddCacheManager(x => {x.WithDictionaryHandle();})
.AddPolly();
}
在configuration.json文件需添加
"AuthenticationOptions":{
"AuthenticationProviderKey":"gatewayKey", // 与startup.cs中ConfigureServices的一致
"AllowedScopes":[]
}
最终使用代码如下
{
"ReRoutes": [
{
"DownstreamPathTemplate": "/api/{url}",
"DownstreamScheme": "http",
"UpstreamPathTemplate": "/up/{url}",
"UpstreamHttpMethod": [ "Get", "Post" ],
"UseServiceDiscovery": true,
"ServiceName": "xing",
"LoadBalancerOptions": {
"Type": "RoundRobin"
},
"FileCacheOptions": {
"TtlSeconds": 15,
"Region": "UserCache"
},
"AuthenticationOptions":{
"AuthenticationProviderKey":"gatewayKey", // 与startup.cs中ConfigureServices的一致
"AllowedScopes":[]
}
}
],
"GlobalConfiguration": {
"BaseUrl": "http://127.0.0.1:9000",
"ServiceDiscoveryProvider": {
"Host": "localhost",
"Port": 8500,
"Type": "Consul"
}
}
}
运行gateway项目;运行ids4项目。用postman访问gateway接口
dotnet gateway.dll --urls="http://*:9000" --ip="127.0.0.1" --port=9000
没有携带token请求如下图
携带token请求如下图