一日一技:Ocelot网关使用IdentityServer4认证
生活随笔
收集整理的這篇文章主要介紹了
一日一技:Ocelot网关使用IdentityServer4认证
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
概述
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 p){List<ApiResource> resource = new List<ApiResource>();if (p != null){List<ApiConfig> configs = new List<ApiConfig>();p.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 p){List<Client> clients = new List<Client>();if (p != null){List<ClientConfig> configs = new List<ClientConfig>();p.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 p = Configuration.GetSection("SSOConfig");services.AddIdentityServer().AddDeveloperSigningCredential().AddInMemoryApiResources(SSOConfig.GetApiResources(p)).AddInMemoryClients(SSOConfig.GetClients(p));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訪問接口
總結
以上是生活随笔為你收集整理的一日一技:Ocelot网关使用IdentityServer4认证的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 浏览器缓存机制的研究分享
- 下一篇: 联想继续为其硬件产品完善Linux支持