Skip to content

Observe the route template constraints in the Swagger middleware#2418

Merged
martincostello merged 4 commits into
domaindrivendev:masterfrom
0xced:route-template-constraints
Apr 18, 2024
Merged

Observe the route template constraints in the Swagger middleware#2418
martincostello merged 4 commits into
domaindrivendev:masterfrom
0xced:route-template-constraints

Conversation

@0xced

@0xced 0xced commented May 18, 2022

Copy link
Copy Markdown
Contributor

The default route template, i.e. swagger/{documentName}/swagger.{json|yaml} which is used by the SwaggerMiddleware is problematic because it matches any file extension. Even though it looks like only json and yaml extensions are supported, actually any extension matches. Trying to hit the following endpoints all return the JSON swagger document:

  • swagger/v1/swagger.xml
  • swagger/v1/swagger.yml
  • swagger/v1/swagger.anything

This is not a very big deal, until the SwaggerUIMiddleware is also used and one chooses to modify the default route to swagger/{documentName}.{json|yaml}.

This is the problematic configuration:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMvcCore().AddApiExplorer();
builder.Services.AddSwaggerGen(c => c.SwaggerDoc("v1", new OpenApiInfo { Title = "Test API", Version = "1" }));
var app = builder.Build();

app.UseSwagger(c => c.RouteTemplate = "swagger/{documentName}.{json|yaml}");
app.UseSwaggerUI(c => c.SwaggerEndpoint("v1.json", "Test API"));

app.Run();

At this point, the SwaggerMiddleware will try to serve swagger/index.html because the route template matches (documentName = index and json|yaml = html) but the index document doesn't exist and this results in a 404 instead of calling the next (SwaggerUI) middleware.

To fix this issue, the default route template has been modified to swagger/{documentName}/swagger.{extension:regex(^(json|ya?ml)$)}, leveraging ASP.NET Core route constraints and the constraints are actually enforced in the SwaggerMiddleware implementation.

The default route template has also been modified in the MapSwagger method to ensure that only json, yaml and yml extensions are supported by default.

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants