RicoSuter / NSwag

The Swagger/OpenAPI toolchain for .NET, ASP.NET Core and TypeScript.
http://NSwag.org
MIT License
6.62k stars 1.23k forks source link

Sending XSRF header when using Swagger UI #4814

Closed chekm8 closed 4 months ago

chekm8 commented 4 months ago

I'm in the process of migrating out of the Swashbuckle implementation and over to NSwag.

In Swashbuckle we utilized a feature "UseRequestInterceptor" which allowed us call a pre-request script to grab the XSRF value and send it as part of the header on the client calls. I never really liked this but, it severed its purpose. The code looked something like this in simple form:

app.UseSwaggerUI(c =>
{
    const string fn =
        $"(request) => {{ var cv = document.cookie.split('; ').filter(row => row.startsWith('{AntiforgeryValidationMiddleware.HeaderName}=')).map(c => c.split('=')[1])[0]; " +
        $"request.headers['{AntiforgeryValidationMiddleware.HeaderName}'] = cv; return request; }}";
    c.UseRequestInterceptor(fn);
});

I would like to replicate something like this using NSwag but I'm not sure if the capability is available. I found the IOperationProcessor but couldn't find an example of what I am trying to do. I would like to avoid creating my own index.html if possible.

Are there any examples using NSwag of grabbing a value client-side and pushing it to a header prior to the API call from swagger UI?

chekm8 commented 4 months ago

I am going to close this as I found a work around.
I used the CustomHeadContent feature to specify a script: app.UseSwaggerUi(c => c.CustomHeadContent = @"<script src='./Scripts/AntiForgery.js' charset='UTF-8'> </script>");

I then embedded a js script in my project that overrides performed the window.fetch utilized by swagger, added the header and all was well in the world :)