如何在SwagguerUI中为API请求添加http头



我有一个web后端生成一个swagger json为我的API。我正在用html和javascript生成我的swagger ui页面,如下所示:

<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',
});

我正在使用SSO解决方案,我有一个令牌变量,我需要通过http头

传递给我的APII've try:

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));
}

但是查询不被拦截。

有办法做到这一点吗?注意:不需要更改后端(和swagger json文件)的解决方案是首选的。

感谢

解决方案是使用requestInterceptor为所有请求(除了加载swagger spec json文件)添加头:

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;
}
});
}