Let's talk about Ocelot gateway using IdentityServer4 authentication

Let's talk about Ocelot gateway using IdentityServer4 authentication

  [[387801]]

This article is reprinted from the WeChat public account "UP Technology Control", the author is conan5566. Please contact the UP Technology Control public account for reprinting this article.

Overview

Ocelot is an open source API gateway technology implemented in .NET Core. IdentityServer4 is a framework for ASP.NET Core based on OpenID Connect and OAuth2.0, which exists in the form of middleware. OAuth is an authorization mechanism. The system generates a short-term token to replace the password for use by third-party applications.

Let's take a look at how to implement Ocelot's unified authentication based on IdentityServer4.

Main code implementation

1. Create a new authentication project and install id4 using nuget

2. appsettings.json configuration

  1. {
  2. "Logging" : {
  3. "LogLevel" : {
  4. "Default" : "Warning"  
  5. }
  6. },
  7. "SSOConfig" : {
  8. "ApiResources" : [
  9. {
  10. "Name" : "testapi" ,
  11. "DisplayName" : "testapiname"  
  12. }
  13. ],
  14. "Clients" : [
  15. {
  16. "ClientId" : "a" ,
  17. "ClientSecrets" : [ "aa" ],
  18. "AllowedGrantTypes" : "ClientCredentials" ,
  19. "AllowedScopes" : [ "testapi" ]
  20. }
  21. ]
  22. },
  23. "AllowedHosts" : "*"  
  24. }
  1. public   static IEnumerable<ApiResource> GetApiResources(IConfigurationSection section )
  2. {
  3. List<ApiResource> resource = new List<ApiResource>();
  4. if ( section != null )
  5. {
  6. List<ApiConfig> configs = new List<ApiConfig>();
  7. section .Bind( "ApiResources" , configs);
  8. foreach (var config in configs)
  9. {
  10. resource. Add (new ApiResource(config. Name , config.DisplayName));
  11. }
  12. }
  13. return resource.ToArray();
  14. }
  15.  
  16. /// <summary>
  17. /// Define trusted client Client
  18. /// </summary>
  19. /// < returns ></ returns >
  20. public   static IEnumerable<Client> GetClients(IConfigurationSection section )
  21. {
  22. List<Client> clients = new List<Client>();
  23. if ( section != null )
  24. {
  25. List<ClientConfig> configs = new List<ClientConfig>();
  26. section .Bind( "Clients" , configs);
  27. foreach (var config in configs)
  28. {
  29. Client client = new Client();
  30. client.ClientId = config.ClientId;
  31. List<Secret> clientSecrets = new List<Secret>();
  32. foreach (var secret in config.ClientSecrets)
  33. {
  34. clientSecrets.Add (new Secret(secret.Sha256()));
  35. }
  36. client.ClientSecrets = clientSecrets.ToArray();
  37. GrantTypes grantTypes = new GrantTypes();
  38. var allowedGrantTypes = grantTypes.GetType().GetProperty(config.AllowedGrantTypes);
  39. client.AllowedGrantTypes = allowedGrantTypes == null ?
  40. GrantTypes.ClientCredentials: (ICollection<string>)allowedGrantTypes.GetValue(grantTypes, null );
  41. client.AllowedScopes = config.AllowedScopes.ToArray();
  42. clients.Add (client) ;
  43. }
  44. }
  45. return clients.ToArray();
  46. }

3. Startup configuration

  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3. var section = Configuration.GetSection( "SSOConfig" );
  4. services.AddIdentityServer()
  5. .AddDeveloperSigningCredential()
  6. .AddInMemoryApiResources(SSOConfig.GetApiResources( section ))
  7. .AddInMemoryClients(SSOConfig.GetClients( section ));
  8. services.AddControllers().SetCompatibilityVersion(CompatibilityVersion.Latest);
  9. }
  10.  
  11. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  12. public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  13. {
  14. if (env.IsDevelopment())
  15. {
  16. app.UseDeveloperExceptionPage();
  17. }
  18.  
  19. app.UseRouting();
  20.  
  21. // app.UseAuthorization();
  22. app.UseIdentityServer();
  23.  
  24. app.UseEndpoints(endpoints =>
  25. {
  26. endpoints.MapControllers();
  27. });
  28. }

4. Gateway project configuration

  1. <ItemGroup>
  2. <PackageReference Include= "IdentityServer4.AccessTokenValidation" Version= "3.0.1" />
  3. <PackageReference Include= "Ocelot" Version= "14.0.3" />
  4. </ItemGroup>
  1. {
  2. "DownstreamPathTemplate" : "/connect/token" ,
  3. "DownstreamScheme" : "http" ,
  4. "DownstreamHostAndPorts" : [
  5. {
  6. "Host" : "localhost" ,
  7. "Port" : 5002
  8. }
  9. ],
  10. "UpstreamPathTemplate" : "/token" ,
  11. "UpstreamHttpMethod" : [ "Post" ],
  12. "Priority" : 2
  13. },
  1. var identityBuilder = services.AddAuthentication();
  2. IdentityServerConfig identityServerConfig = new IdentityServerConfig();
  3. Configuration.Bind( "IdentityServerConfig" , identityServerConfig);
  4. if (identityServerConfig != null && identityServerConfig.Resources != null )
  5. {
  6. foreach (var resource in identityServerConfig.Resources)
  7. {
  8. identityBuilder.AddIdentityServerAuthentication( resource.Key , options =>
  9. {
  10. options.Authority = $ "http://{identityServerConfig.IP}:{identityServerConfig.Port}" ;
  11. options.RequireHttpsMetadata = false ;
  12. options.ApiName = resource.Name ;
  13. options.SupportedTokens = SupportedTokens.Both;
  14. });
  15. }
  16. }
  17.  
  18. // services.AddControllers();
  19. services.AddOcelot(Configuration);

test

1. No token is added for access, 401 is returned

2. Get access token

3. Access the interface with token

<<:  315 Gala: Mobile phone cleaning software pushes the elderly into the abyss of fraud

>>:  How to avoid safety traps when using mobile phones for the elderly? Remember these "iron rules"

Recommend

Prospects and challenges of 5G messaging development

With the rapid development and popularization of ...

Summary and analysis of the top ten optical communication technologies in 2016

5G channel coding technology In October 2016, Hua...

PM Experience Talks About the 5 Essential Features of Project Management Tools

【51CTO.com Quick Translation】 Project management ...

Overview of the five major 5G wireless technologies

Two of the five most important wireless technolog...

Reconnect the campus network after it is disconnected. Use crawlers to fix it!

[[433698]] Preface Hello, everyone. I am Dasai Ge...

Comparative Analysis of Kubernetes Network Plugins (Flannel, Calico, Weave)

[[269494]] This article will focus on exploring a...

How much do you know about the legendary network speed limit?

1. Recently, many people have said that the unlim...

Introduction and solution of TCP sticky packet and half packet (Part 1)

In network transmission, sticky packets and half ...

Outlook for domestic 5G development in 2021 (Part 2): Challenges

Relying on its significant advantages of high spe...

5G technology has just emerged, so don’t rush to pour cold water on it

After 3G and 4G have successively gone from unfam...

Mercury enables remote procedure calls (RPC) for high performance computing

summary Remote Procedure Call (RPC) is a widely u...