ThreeMammals / Ocelot

.NET API Gateway
https://www.nuget.org/packages/Ocelot
MIT License
8.28k stars 1.63k forks source link

How to find servicename on PreAuthorizationMiddleware #1978

Closed Iran-asp closed 5 months ago

Iran-asp commented 5 months ago

Imagine a scenario (I know it seems odd but unfortunately it’s real!) that clients want to use one upstream (e.g., http://api.qwe.com/v1/sms) to send SMS with some SMS providers, but in the background it automatically identifies the related subservice based on the scope parameter on the JWT token and not to use separated URLs for each one (e.g., …/sms/provider1 - …/sms/provider2). I searched the net and I decided to add this functionality into the Ocelot API Gateway (maybe it’s wrong, actually I’m not sure…). There are some samples that says we can add this functionality to the PreAuthorizationMiddleware. For example:

public void Configure(IApplicationBuilder app)
{
    var conf = new OcelotPipelineConfiguration
    {
              PreAuthorizationMiddleware = async (httpContext, next) =>
              {
                  var claims = httpContext.User.Claims;
                  if (claims != null)
                  {
                      var scopes = claims.Where(x => x.Type == "scope").Select(x => x.Value);
                      if (scopes != null)
                      {
                          // Override the downstream request settings
                          var downstreamRequest = httpContext.Items.DownstreamRequest();
                          downstreamRequest.Host = downstreamRequest.Host;
                          downstreamRequest.Port = downstreamRequest.Port;
                          downstreamRequest.Scheme = downstreamRequest.Scheme;
                          // DO OTHER THINGS
                      }
                  }
              }
    };

    builder.Services.AddOcelot(conf).AddConsul();
}

As it shows, they use downstreamRequest.Host and downstreamRequest.Port to find sub-services, but what should you do if you use Consul as service discovery? As you know, in this situation Ocelot will use service discovery with ServiceName to find sub-services. The main question is how can I tell Ocelot to use Consul instead of Host:Port? If you have a moment, I’d appreciate your help.

raman-m commented 5 months ago

Hi Shadman! Welcome to Ocelot world! 🐯

But you had to create the question in Discussions space! Converting to discussion...