Skip to content

Instantly share code, notes, and snippets.

@chvjak
Last active May 1, 2025 14:12
Show Gist options
  • Save chvjak/6cabd7c1c774c1c2adfacbda6695ffc4 to your computer and use it in GitHub Desktop.
Save chvjak/6cabd7c1c774c1c2adfacbda6695ffc4 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Swagger Auto-Login on 401 (Verbose)
// @namespace http://tampermonkey.net/
// @version 1.3
// @description Opens Swagger UI login dialog automatically if 401 Unauthorized response recieved
// @match *://*/swagger*
// @grant none
// ==/UserScript==
(function () {
'use strict';
console.info('[TM-Swagger401] Script initialized');
function openAuthorizeDialog(retries = 10, delay = 500) {
let attempts = 0;
(function tryClick() {
const btn = document.querySelector('.swagger-ui .auth-wrapper .authorize');
if (btn) {
btn.click();
} else if (attempts++ < retries) {
setTimeout(tryClick, delay);
} else {
console.error('[TM-Swagger401] Authorize button not found after retries');
}
})();
}
const originalFetch = window.fetch;
window.fetch = async function (...args) {
console.debug('[TM-Swagger401] fetch:', args);
try {
const res = await originalFetch.apply(this, args);
if (res.status === 401) {
console.warn(`[TM-Swagger401] 401 from fetch ${args[0]}`);
openAuthorizeDialog();
}
return res;
} catch (err) {
console.error('[TM-Swagger401] fetch error:', err);
throw err;
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment