Finding ServiceName in PreAuthorizationMiddleware of Ocelot Api-Gateway

12 Views Asked by At

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). So I decided to add this functionality into the Ocelot API Gateway (maybe it’s wrong, actually I’m not sure…) because I think it might be better to handle requests on API-Gateway instead of a middle-Service or microservices.

There are some samples that says we can add this functionality to the PreAuthorizationMiddleware. For example:

    var config = 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;
                }
            }
        }
    };
    builder.Configuration.AddJsonFile("Ocelot.json", optional: false, reloadOnChange: true);
    builder.Services.AddOcelot(config).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.

0

There are 0 best solutions below