Search code examples
asp.net-coreswaggercsrfswagger-uiswashbuckle

How to include X-XSRF-TOKEN header in Swagger UI?


I have a .NET Core 3.1 Web API that I want to add XSRF protection to. So I now require an antiforgery token in an X-XSRF-TOKEN HTTP header on all of my endpoints as described here. JavaScript clients get a token by hitting the /antiforgerytoken endpoint, which sets an XSRF-TOKEN cookie containing the token. This all works fine, but as one would expect, the "Try it out!" feature in Swagger UI no longer works since the requests are missing the X-XSRF-TOKEN HTTP header. Is there a way to have SwaggerUI automatically call the /antiforgerytoken endpoint and include the token in the request being executed?


Solution

  • On Swagger UI, this can be supported by setting a requestInterceptor on the configuration which is a function that intercepts and modifies outgoing requests, including "Try it out" requests. See this comment in Swagger UI repo and the README on Swagger UI configuration.

    However, Swashbuckle.AspNetCore.SwaggerUI does not yet support setting requestInterceptor in C# as of the latest stable release (5.6.3). There is this PR that added support for interceptors, and it has been merged but not yet released. So if you are using Swashbuckle.AspNetCore.SwaggerUI, your options for now is to wait for the next release, or build from source a local version before the next official release.