本文共 3885 字,大约阅读时间需要 12 分钟。
在上一篇文章中,我们已经探讨了基于Consul服务集群和Ocelot网关集群的微服务架构。虽然看似完美,但实际上只是解决了那篇文章的特定问题。每篇文章都聚焦于一个核心问题,这样可以帮助读者更清晰地理解每个技术点。今天,我们将重点解决认证和授权问题,确保服务实例不再裸奔在互联网上。
我们的目标是构建一个基于Consul集群、Ocelot网关集群和IdentityServer4的微服务架构。通过这种架构,我们可以为服务实例添加安全防护,防止未经授权的访问。实际项目中,大多数服务并非对外开放,而是需要特定权限才能访问。我们将从以下几个方面入手:
首先,我们需要一个测试项目来展示各个技术的实现。这个项目的代码简单明了,主要为了突出Consul、Ocelot和IdentityServer4的功能。
在生产环境中,单独运行Consul节点无法满足高可用性需求。因此,我们需要部署Consul集群。Consul使用Raft协议进行数据一致性,确保服务发现的高可用性。
下载Consul:从官方网站下载Consul.exe。
部署Consul节点:
验证集群状态:
consul members命令查看节点状态。consul operator raft list-peers检查Raft网络。Ocelot是一个功能强大的.NET Core网关,可以通过JSON配置实现路由、负载均衡、认证和限流等功能。
services.AddOcelot() .AddConsul() .AddCacheManager(builder => builder.WithDictionaryHandle()) .AddPolly();
{ "Routes": [ { "DownstreamPathTemplate": "/api/{url}", "DownstreamScheme": "http", "UpstreamPathTemplate": "/gate/{url}", "UpstreamHttpMethod": ["Get", "Post"], "UseServiceDiscovery": true, "ServiceName": "PatrickLiuService", "LoadBalancerOptions": { "Type": "RoundRobin" } } ], "GlobalConfiguration": { "BaseUrl": "http://localhost:6299", "ServiceDiscoveryProvider": { "Host": "localhost", "Port": 8090, "Type": "Consul", "PollingInterval": 1000, "Token": "footoken" } }}dotnet run命令启动Ocelot服务。IdentityServer4是用于开源认证与授权的强大工具。我们需要配置它并与Ocelot网关集成。
安装IdentityServer4:使用NuGet安装IdentityServer4和相关插件。
配置Startup.cs:
services.AddAuthentication("Bearer") .AddIdentityServerAuthentication("UserGatewayKey", options => { options.Authority = "http://localhost:7299"; options.ApiName = "UserApi"; options.RequireHttpsMetadata = false; options.SupportedTokens = SupportedTokens.Both; });创建客户端配置:
public class ClientInitConfig{ public static IEnumerable GetApiScopes() => new List { new ApiScope(name: "User.Get", displayName: "获取用户数据"), new ApiScope(name: "Health.Check", displayName: "健康检查") }; public static IEnumerable GetApiResources() => new List { new ApiResource("UserApi", "Invoice API") { Scopes = new[] { "User.Get", "Health.Check" } } }; public static IEnumerable GetClients() => new List { new Client { ClientId = "PatrickLiu.MicroService.AuthenticationDemo", ClientSecrets = new[] { new Secret("PatrickLiu123456".Sha256()) }, AllowedGrantTypes = GrantTypes.ClientCredentials, AllowedScopes = new[] { "User.Get", "Health.Check" }, Claims = new List { new ClientClaim(IdentityModel.JwtClaimTypes.Role, "Admin"), new ClientClaim(IdentityModel.JwtClaimTypes.NickName, "PatrickLiu"), new ClientClaim("eMail", "PatrickLiu@sina.com") } } };} 启动认证中心:通过dotnet run命令启动IdentityServer4。
dotnet run命令启动每个服务实例。通过以上步骤,我们成功搭建了一个基于Consul集群、Ocelot网关和IdentityServer4的微服务架构。虽然当前版本已经实现了基本功能,但还有许多优化空间。例如,Token过期机制可以进一步精简,客户端集成可以添加更多细节。接下来,我们将将所有服务迁移到Linux服务器,并使用Docker进行虚拟化部署,这将是下一篇文章的重点。
转载地址:http://qwukz.baihongyu.com/