0

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

Loic
  • 3,310
  • 4
  • 25
  • 43
  • Swagger UI has the `requestInterceptor` config for this purpose, check the 2nd example [in this answer](https://stackoverflow.com/a/49424494/113116). – Helen Apr 03 '23 at 14:51
  • @Helen thak you it's working! I just had to replace 'Basic' by 'Bearer' If you want to write the answer I will mark it as accepted for sure – Loic Apr 04 '23 at 14:25

1 Answers1

1

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;
            }
        });
    }
Loic
  • 3,310
  • 4
  • 25
  • 43