From 87b684d79a5d8f2a3782b8933febad8e2f866810 Mon Sep 17 00:00:00 2001 From: Maarten Balliauw Date: Wed, 19 Mar 2025 09:55:57 +0100 Subject: [PATCH] Add Swagger support for API documentation in development Integrated Swashbuckle for API documentation and updated service configuration to include Swagger and Swagger UI. Added middleware to handle anti-forgery headers for Swagger UI requests in development mode. --- .../FrontendHost/FrontendHost.csproj | 2 ++ BFF/v3/JsBffSample/FrontendHost/Program.cs | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/BFF/v3/JsBffSample/FrontendHost/FrontendHost.csproj b/BFF/v3/JsBffSample/FrontendHost/FrontendHost.csproj index 83a4b445..4e118929 100644 --- a/BFF/v3/JsBffSample/FrontendHost/FrontendHost.csproj +++ b/BFF/v3/JsBffSample/FrontendHost/FrontendHost.csproj @@ -10,6 +10,8 @@ + + diff --git a/BFF/v3/JsBffSample/FrontendHost/Program.cs b/BFF/v3/JsBffSample/FrontendHost/Program.cs index 782129a3..cc058e08 100644 --- a/BFF/v3/JsBffSample/FrontendHost/Program.cs +++ b/BFF/v3/JsBffSample/FrontendHost/Program.cs @@ -1,8 +1,13 @@ +using Duende.Bff; using Duende.Bff.Yarp; +using Microsoft.Extensions.Options; +using Swashbuckle.AspNetCore.SwaggerUI; var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); builder.Services.AddBff() .AddRemoteApis(); @@ -58,6 +63,24 @@ app.UseRouting(); app.UseAuthentication(); + +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); + + app.Use(async (context, next) => + { + var swaggerUIOptions = context.RequestServices.GetRequiredService>().Value; + if (context.Request.Headers.Referer.Any(it => it.EndsWith($"/{swaggerUIOptions.RoutePrefix}/index.html"))) + { + var bffOptions = context.RequestServices.GetRequiredService>().Value; + context.Request.Headers[bffOptions.AntiForgeryHeaderName]= bffOptions.AntiForgeryHeaderValue; + } + await next(); + }); +} + app.UseBff(); app.UseAuthorization();