Search code examples
javascriptsecurityswagger

How to add http headers to API requests in SwagguerUI


I have a web backend generating a swagger json for my API. I am generating my swagger ui page with html and javascript like so :

  <div id="swagger-ui"></div>

  <script src="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui-bundle.js" crossorigin></script>
  <link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@4.5.0/swagger-ui.css" />

  window.ui = SwaggerUIBundle({
    url: '/api-docs',
    dom_id: '#swagger-ui',
  });

I am using a SSO solution and I have a token variable I need to pass to my API through http header

I've tried :

self.addEventListener("fetch", (event) => {

if (event.request.url.includes('/api'){
    var newRequest = new Request(event.request, {
        mode: "cors",
        headers: {
            "Accept" : "application/json",
            "Authorization" : "Bearer " + token
        }
    });
    event.respondWith(fetch(newRequest));
}

But queries are not intercept.

Is there a way to do this? Note : a solution without having to change the backend (and the swagger json file) would be prefered.

Thanks


Solution

  • The solution is to use requestInterceptor to add headers to all requests (except to load swagger spec json file) :

    function initSwagger(keycloak){    
            window.ui = SwaggerUIBundle({
                url: '/api-docs',
                dom_id: '#swagger-ui',
                requestInterceptor: (req) => {
                  if (! req.loadSpec) {
                    req.headers.Authorization = "Bearer " + keycloak.token;
                  }
                  return req;
                }
            });
        }