I'd like to share with you how I solved this issue... and if you have comments or suggestions they are more than welcome ;-)
var appId = "swagger-ui"
window.authorizations.add("authToken", new TokenAuthorization(appId, null, null, null));
$('#input_authToken').change(function() {
var authToken = $('#input_authToken')[0].value;
if (authToken && authToken.trim() != "") log("added authToken " + authToken);
window.authorizations.add("authToken", new TokenAuthorization(appId, authToken, null, null));
})
window.swaggerUi.load();
var TokenAuthorization = function(appId, token, type, expirationTime) {
this.appId = appId;
this.token = token;
this.type = type;
this.expirationTime = expirationTime;
this.locked = false
};
TokenAuthorization.prototype.lock = function() {
this.locked = true;
};
TokenAuthorization.prototype.unlock = function() {
this.locked = false;
};
TokenAuthorization.prototype.apply = function(obj, authorizations) {
var now = Math.round(new Date().getTime() / 1000);
if (!this.locked && (this.token == null || (this.type == "browse" && this.expirationTime <= now))) {
var baseUrl = obj.url.split("api-docs")[0] + "auth";
var appId = this.appId;
this.lock();
$.ajax({
type: "GET",
url: baseUrl + "/apps/" + appId + "/apikey"
}).done(function(result) {
$.ajax({
type: "POST",
data: JSON.stringify({ principal: appId, secret: result.apiKey }),
url: baseUrl + "/apps/credentials",
contentType: "application/json"
}).done(function(result) {
var token = result.token;
$.ajax({
type: "GET",
headers: { "Authorization": "Token " + token },
url: baseUrl + "/users/credentials"
}).done(function(result) {
e.authorizations.add("authToken", new TokenAuthorization(
appId, token,
result.token.header.typ.split('/')[1],
result.token.claims.exp
));
log("browse token: " + token);
obj.headers["Authorization"] = "Token " + token;
})
})
});
} else if (!this.locked) {
obj.headers["Authorization"] = "Token " + this.token;
}
return true;
};
The code above performs three REST calls to eventually get a JWT (JSON Web Token) to be used by the current API consumer (i.e. swagger-ui) to browse the API. Once a browse token expires, a new one is requested automatically... and since the secret API key changes many times a day, the three REST calls have to be performed again. When the user signs in, the browse token is no longer needed the any subsequent request is performed with an authorization token.