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请求如下图
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义