From c9f9b70b67e0f44b467b5206ca5d2301988bad51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jordi=20Guti=C3=A9rrez=20Hermoso?= Date: Thu, 25 Jul 2024 23:01:55 -0400 Subject: [PATCH] apiconsole: allow uploads in console By adding an XHR to "Try it out" requests, we can make non-JSON requests pass a CORS check. --- app/client/apiconsole.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/app/client/apiconsole.ts b/app/client/apiconsole.ts index 0a888173..98bb59c0 100644 --- a/app/client/apiconsole.ts +++ b/app/client/apiconsole.ts @@ -293,6 +293,25 @@ function initialize(appModel: AppModel) { function requestInterceptor(request: SwaggerUI.Request) { delete request.headers.Authorization; + const url = new URL(request.url); + // Swagger will use this request interceptor for several kinds of + // requests, such as requesting the API YAML spec from Github: + // + // Function to intercept remote definition, "Try it out", + // and OAuth 2.0 requests. + // + // https://swagger.io/docs/open-source-tools/swagger-ui/usage/configuration/ + // + // We want to ensure that only "Try it out" requests have XHR, so + // that they pass a same origin request, even if they're not GET, + // HEAD, or OPTIONS. "Try it out" requests are the requests to the + // same origin. + if (url.origin === window.origin) { + // Without this header, unauthenticated multipart POST requests + // (i.e. file uploads) would fail in the API console. We want those + // requests to succeed. + request.headers['X-Requested-With'] = 'XMLHttpRequest'; + } return request; }