-
Notifications
You must be signed in to change notification settings - Fork 1.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Allow CORS on swagger.json endpoint only #2078
Labels
Comments
I create a pr for this. before merged, the solution is creating a extensions method. public static IEndpointConventionBuilder MapSwagger(
this IEndpointRouteBuilder endpoints,
string pattern = "/swagger/{documentName}/swagger.json",
Action<SwaggerEndpointOptions> setupAction = null)
{
if (!RoutePatternFactory.Parse(pattern).Parameters.Any(x => x.Name == "documentName"))
{
throw new ArgumentException("Pattern must contain '{documentName}' parameter", nameof(pattern));
}
Action<SwaggerOptions> endpointSetupAction = options =>
{
var endpointOptions = new SwaggerEndpointOptions();
setupAction?.Invoke(endpointOptions);
options.RouteTemplate = pattern;
options.SerializeAsV2 = endpointOptions.SerializeAsV2;
options.PreSerializeFilters.AddRange(endpointOptions.PreSerializeFilters);
};
var pipeline = endpoints.CreateApplicationBuilder()
.UseSwagger(endpointSetupAction)
.Build();
return endpoints.MapGet(pattern, pipeline);
} Update your app.UseEnpoint(endpoint=>{
endpoint.MapSwagger().RequireCors();
}); |
Thanks for your reply and pull request. I finally took time to test your extension method and everything work. |
Hi, can you share your sample code? I can't make it work. Thanks. |
martincostello
added
the
help-wanted
A change up for grabs for contributions from the community
label
May 4, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Labels
I can't find a way to enable CORS on the swagger.json endpoint only whithout applying CORS for whole API.
I read the documentation here : https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors-with-attributes and I understand how I can enable cors for the whole API including the swagger.json endpoint but my external application only need to access my swagger.json definition.
It would be a nice feature if we can specify the CORS policy for the swagger.json endpoint :
something like
or maybe
This question has also been posted on stackoverflow here : https://stackoverflow.com/questions/60232282/add-cors-policy-for-swagger-endpoints-only
The text was updated successfully, but these errors were encountered: