本文转载自微信公众号「UP技术控」,作者conan5566 。转载本文请联系UP技术控公众号。
概述
Ocelot是一个用.NET Core实现的开源API网关技术。IdentityServer4是一个基于OpenID Connect和OAuth2.0的针对ASP.NET Core的框架,以中间件的形式存在。OAuth是一种授权机制。系统产生一个短期的token,用来代替密码,供第三方应用使用。
下面来看下如何实现Ocelot基于IdentityServer4统一认证。
1、新建认证项目,nuget安装id4
2、appsettings.json 配置
- {
- "Logging": {
- "LogLevel": {
- "Default": "Warning"
- }
- },
- "SSOConfig": {
- "ApiResources": [
- {
- "Name": "testapi",
- "DisplayName": "testapiname"
- }
- ],
- "Clients": [
- {
- "ClientId": "a",
- "ClientSecrets": [ "aa" ],
- "AllowedGrantTypes": "ClientCredentials",
- "AllowedScopes": [ "testapi" ]
- }
- ]
- },
- "AllowedHosts": "*"
- }
- public static IEnumerable<ApiResource> GetApiResources(IConfigurationSection section)
- {
- List<ApiResource> resource = new List<ApiResource>();
- if (section != null)
- {
- List<ApiConfig> configs = new List<ApiConfig>();
- section.Bind("ApiResources", configs);
- foreach (var config in configs)
- {
- resource.Add(new ApiResource(config.Name, config.DisplayName));
- }
- }
- return resource.ToArray();
- }
- /// <summary>
- /// 定义受信任的客户端 Client
- /// </summary>
- /// <returns></returns>
- public static IEnumerable<Client> GetClients(IConfigurationSection section)
- {
- List<Client> clients = new List<Client>();
- if (section != null)
- {
- List<ClientConfig> configs = new List<ClientConfig>();
- section.Bind("Clients", configs);
- foreach (var config in configs)
- {
- Client client = new Client();
- client.ClientId = config.ClientId;
- List<Secret> clientSecrets = new List<Secret>();
- foreach (var secret in config.ClientSecrets)
- {
- clientSecrets.Add(new Secret(secret.Sha256()));
- }
- client.ClientSecrets = clientSecrets.ToArray();
- GrantTypes grantTypes = new GrantTypes();
- var allowedGrantTypes = grantTypes.GetType().GetProperty(config.AllowedGrantTypes);
- client.AllowedGrantTypes = allowedGrantTypes == null ?
- GrantTypes.ClientCredentials : (ICollection<string>)allowedGrantTypes.GetValue(grantTypes, null);
- client.AllowedScopes = config.AllowedScopes.ToArray();
- clients.Add(client);
- }
- }
- return clients.ToArray();
- }
3、Startup 配置
- public void ConfigureServices(IServiceCollection services)
- {
- var section = Configuration.GetSection("SSOConfig");
- services.AddIdentityServer()
- .AddDeveloperSigningCredential()
- .AddInMemoryApiResources(SSOConfig.GetApiResources(section))
- .AddInMemoryClients(SSOConfig.GetClients(section));
- services.AddControllers().SetCompatibilityVersion(CompatibilityVersion.Latest);
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- app.UseRouting();
- // app.UseAuthorization();
- app.UseIdentityServer();
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
4、网关项目配置
- <ItemGroup>
- <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="3.0.1" />
- <PackageReference Include="Ocelot" Version="14.0.3" />
- </ItemGroup>
- {
- "DownstreamPathTemplate": "/connect/token",
- "DownstreamScheme": "http",
- "DownstreamHostAndPorts": [
- {
- "Host": "localhost",
- "Port": 5002
- }
- ],
- "UpstreamPathTemplate": "/token",
- "UpstreamHttpMethod": [ "Post" ],
- "Priority": 2
- },
- var identityBuilder = services.AddAuthentication();
- IdentityServerConfig identityServerConfig = new IdentityServerConfig();
- Configuration.Bind("IdentityServerConfig", identityServerConfig);
- if (identityServerConfig != null && identityServerConfig.Resources != null)
- {
- foreach (var resource in identityServerConfig.Resources)
- {
- identityBuilder.AddIdentityServerAuthentication(resource.Key, options =>
- {
- options.Authority = $"http://{identityServerConfig.IP}:{identityServerConfig.Port}";
- options.RequireHttpsMetadata = false;
- options.ApiName = resource.Name;
- options.SupportedTokens = SupportedTokens.Both;
- });
- }
- }
- // services.AddControllers();
- services.AddOcelot(Configuration);
1、没有添加token访问,返回401
2、获取访问的token
3、带上token访问接口
1.总有一天,我们会过上我一翻身就可以偷亲你的日子。 2.即使一贫如洗,我会是...
逛个动物园要指纹打卡,连回家进小区也要刷脸验明正身会议期间,记者在浙江代表...
1.终有那么一个人,可以随时改变着你的心情。 2.有的东西你再喜欢也不会属於你...
3月15日消息 一年一度的央视财经 3.15 晚会正在进行中,从前言来看主要曝光问题...
iOS 11~iOS 14.3的越狱工具发布了un0ver6.0.0版本 支持iOS11-iOS 14.3系统设备进...
整个欧洲向智能建筑迈进的步伐正在加快。随着各行各业的组织在客户和员工体验方...
人脸解锁扫脸支付随着人脸识别技术的不断发展,如今借助一个小小的摄像头就能让...
近年来,因高空抛物、坠物造成的伤害事件屡上报端。水瓶、西瓜皮、易拉罐,甚至...
5G切片是新商业模式的关键推动者,也是增强5G潜力的关键概念。通信服务提供商可...
5G网络建设加快,超前布局6G 截止目前,我国累计建成的5G基站数量超过71.8万座,...