andreytreyt / yarp-swagger

It's an easy to use Swagger extension for the YARP project.
MIT License
67 stars 15 forks source link
swagger yarp

dotnet_main release nuget_v nuget_dt

Getting Started

Configure Swagger and YARP for your project.

From Configuration

Update appsettings.json:

{
  "ReverseProxy": {
    "Clusters": {
      "App1Cluster": {
        "Destinations": {
          "Default": {
            "Address": "https://localhost:5101",
            "Swaggers": [ // <-- this block
              {
                "PrefixPath": "/proxy-app1",
                "Paths": [
                  "/swagger/v1/swagger.json"
                ]
              }
            ]
          }
        }
      }
    }
  }
}

Update Program.cs:

var configuration = builder.Configuration.GetSection("ReverseProxy");
builder.Services
    .AddReverseProxy()
    .LoadFromConfig(configuration)
    .AddSwagger(configuration); // <-- this line

From Code

Update Program.cs:

RouteConfig[] GetRoutes()
{
    return new[]
    {
        new RouteConfig
        {
            RouteId = "App1Route",
            ClusterId = "App1Cluster",
            Match = new RouteMatch
            {
                Path = "/proxy-app1/{**catch-all}"
            },
            Transforms = new[]
            {
                new Dictionary<string, string>
                {
                    {"PathPattern", "{**catch-all}"}
                }
            }
        }
    };
}

ClusterConfig[] GetClusters()
{
    return new[]
    {
        new ClusterConfig
        {
            ClusterId = "App1Cluster",
            Destinations = new Dictionary<string, DestinationConfig>
            {
                {
                    "Default", new DestinationConfig
                    {
                        Address = "https://localhost:5101"
                    }
                }
            }
        }
    };
}

ReverseProxyDocumentFilterConfig GetSwaggerConfig()
{
    return new ReverseProxyDocumentFilterConfig
    {
        Routes = GetRoutes().ToDictionary(_ => _.RouteId, _ => _),
        Clusters = new Dictionary<string, ReverseProxyDocumentFilterConfig.Cluster>
        {
            {
                "App1Cluster", new ReverseProxyDocumentFilterConfig.Cluster
                {
                    Destinations = new Dictionary<string, ReverseProxyDocumentFilterConfig.Cluster.Destination>
                    {
                        {
                            "Default", new ReverseProxyDocumentFilterConfig.Cluster.Destination
                            {
                                Address = "https://localhost:5101",
                                Swaggers = new[]
                                {
                                    new ReverseProxyDocumentFilterConfig.Cluster.Destination.Swagger
                                    {
                                        PrefixPath = "/proxy-app1",
                                        Paths = new[] {"/swagger/v1/swagger.json"}
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    };
}

builder.Services
    .AddReverseProxy()
    .LoadFromMemory(GetRoutes(), GetClusters())
    .AddSwagger(GetSwaggerConfig()); // <-- this line

Common

Create (if doesn't exist) or update ConfigureSwaggerOptions.cs:

public void Configure(SwaggerGenOptions options)
{
    var filterDescriptors = new List<FilterDescriptor>();

    foreach (var cluster in _reverseProxyDocumentFilterConfig.Clusters)
    {
        options.SwaggerDoc(cluster.Key, new OpenApiInfo {Title = cluster.Key, Version = cluster.Key});
    }

    filterDescriptors.Add(new FilterDescriptor
    {
        Type = typeof(ReverseProxyDocumentFilter),
        Arguments = Array.Empty<object>()
    });

    options.DocumentFilterDescriptors = filterDescriptors;
}

Update Program.cs:

builder.Services.AddTransient<IConfigureOptions<SwaggerGenOptions>, ConfigureSwaggerOptions>();
builder.Services.AddSwaggerGen();
app.UseSwaggerUI(options =>
{
    var config = app.Services.GetRequiredService<IOptionsMonitor<ReverseProxyDocumentFilterConfig>>().CurrentValue;
    foreach (var cluster in config.Clusters)
    {
        options.SwaggerEndpoint($"/swagger/{cluster.Key}/swagger.json", cluster.Key);
    }
});

After run you will get generated Swagger files by clusters:

image

Authentication and Authorization

Update appsettings.json:

{
  "ReverseProxy": {
    "Clusters": {
      "App1Cluster": {
        "Destinations": {
          "Default": {
            "Address": "https://localhost:5101",
            "AccessTokenClientName": "Identity", // <-- this line
            "Swaggers": [
              {
                "PrefixPath": "/proxy-app1",
                "Paths": [
                  "/swagger/v1/swagger.json"
                ]
              }
            ]
          }
        }
      }
    }
  }
}

Update Program.cs:

builder.Services.AddAccessTokenManagement(options =>
{
    var identityConfig = builder.Configuration.GetSection("Identity").Get<IdentityConfig>()!;

    options.Client.Clients.Add("Identity", new ClientCredentialsTokenRequest
    {
        Address = $"{identityConfig.Url}/connect/token",
        ClientId = identityConfig.ClientId,
        ClientSecret = identityConfig.ClientSecret
    });
});

Filtering of Paths

By Regex Pattern

Update appsettings.json:

{
  "ReverseProxy": {
    "Clusters": {
      "App1Cluster": {
        "Destinations": {
          "Default": {
            "Address": "https://localhost:5101",
            "Swaggers": [
              {
                "PrefixPath": "/proxy-app1",
                "PathFilterRegexPattern": ".*", // <-- this line
                "Paths": [
                  "/swagger/v1/swagger.json"
                ]
              }
            ]
          }
        }
      }
    }
  }
}

By Only Published Paths

If you want to publish only some configured path in YARP, you can use the AddOnlyPublishedPaths option. (For using these options, you need to add Methods configuration in the Match block of the YARP configuration.)

Update appsettings.json:

{
  "ReverseProxy": {
    "Clusters": {
      "App1Cluster": {
        "Destinations": {
          "Default": {
            "Address": "https://localhost:5101",
            "Swaggers": [
              {
                "PrefixPath": "/proxy-app1",
                "AddOnlyPublishedPaths": true, // <-- this line
                "Paths": [
                  "/swagger/v1/swagger.json"
                ]
              }
            ]
          }
        }
      }
    }
  }
}

Swagger Metadata

If you want to publish the API metadata (OpenAPI info object) from the configured swaggers, specify a path from the list of configured paths using the MetadataPath option. This will overwrite the cluster metadata with that of the swagger metadata.

Update appsettings.json:

{
  "ReverseProxy": {
    "Clusters": {
      "App1Cluster": {
        "Destinations": {
          "Default": {
            "Address": "https://localhost:5101",
            "Swaggers": [
              {
                "PrefixPath": "/proxy-app1",
                "MetadataPath": "/swagger/v1/swagger.json", // <-- this line
                "Paths": [
                  "/swagger/v1/swagger.json"
                ]
              }
            ]
          }
        }
      }
    }
  }
}

Common Swagger Document

If you want to combine multiple swagger documents into one, you can use the Swagger option.

Update appsettings.json:

{
  "ReverseProxy": {
    "Swagger": { // <-- this block
      "IsCommonDocument": true,
      "CommonDocumentName": "YARP"
    },
  }
}

Swagger Transformation

If you want to transform the Swagger to fit the modifications done by the transformations you have to implement the changes in the ISwaggerTransformFactory. Below is an example from a custom transformation called RenameHeader.

public class HeaderTransformFactory : ITransformFactory, ISwaggerTransformFactory
{
    public bool Validate(TransformRouteValidationContext context, IReadOnlyDictionary<string, string> transformValues)
    {
        // validation implementation of custom transformation
    }

    public bool Build(TransformBuilderContext context, IReadOnlyDictionary<string, string> transformValues)
    {
        // transform implementation of custom transformation
    }

    /// <summary>
    /// Header title rename transformation for Swagger
    /// </summary>
    /// <param name="operation"></param>
    /// <param name="transformValues"></param>
    /// <returns></returns>
    public bool Build(OpenApiOperation operation, IReadOnlyDictionary<string, string> transformValues)
    {
        if (transformValues.ContainsKey("RenameHeader"))
        {
            foreach (var parameter in operation.Parameters)
            {
                if (parameter.In.HasValue && parameter.In.Value.ToString().Equals("Header"))
                {
                    if (transformValues.TryGetValue("RenameHeader", out var header)
                        && transformValues.TryGetValue("Set", out var newHeader))
                    {
                        if (parameter.Name == newHeader)
                        {
                            parameter.Name = header;
                        }
                    }
                }
            }

            return true;
        }

        return false;
    }
}

Then register the transformation in Program.cs

builder.Services
    .AddReverseProxy()
    .LoadFromConfig(configuration)
    .AddTransformFactory<HeaderTransformFactory>()
    .AddSwagger(configuration)