/**
*
* @module de.stschnell
*
* @version 0.1.0
*
* @param {string} in_userName
* @param {SecureString} in_password
*
* @outputType String
*
*/
function getBearerToken(in_userName, in_password) {
/**
* Delivers the bearer token in the log with the user name and user
* password as parameters.
*
* @author Stefan Schnell <mail@stefan-schnell.de>
* @license MIT
* @version 0.1.0
*
* Set com.vmware.scripting.javascript.allow-native-object in the
* system properties to true.
*
* Checked with VMware Aria Automation 8.12.0.
*
* @example
* var token = System.getModule("de.stschnell").getBearerToken(
* "holadmin@corp.vmbeans.com",
* "VMware1!"
* );
*/
function getFQDN() {
var fqdn = "";
var jvmOpts = java.lang.System.getenv("JVM_OPTS");
if (jvmOpts !== null) {
var options = jvmOpts.split(" ");
options.forEach( function(option) {
if (option.substring(0, 19) === "-Dvco.app.hostname=") {
fqdn = option.substring(19, option.length);
}
});
}
if (fqdn !== "") {
return fqdn;
} else {
return null;
}
}
function retrieveBearerToken(url, username, password) {
var httpRestHost = RESTHostManager.createTransientHostFrom(
RESTHostManager.createHost("dynamicRequest")
);
httpRestHost.operationTimeout = 60;
httpRestHost.connectionTimeout = 30;
httpRestHost.hostVerification = false;
httpRestHost.url = url;
var oLogin = {
"username": username,
"password": password
};
var jsonLogin = JSON.stringify(oLogin);
var request = httpRestHost.createRequest(
"POST",
"/csp/gateway/am/api/login?access_token",
jsonLogin
);
request.contentType = "application/json";
var response = request.execute();
if (response.statusCode === 200) {
var oRefreshToken = JSON.parse(response.contentAsString);
var refreshToken = "{\"refreshToken\":\"" +
oRefreshToken.refresh_token + "\"}";
request = httpRestHost.createRequest(
"POST",
"/iaas/api/login",
refreshToken
);
request.contentType = "application/json";
response = request.execute();
if (response.statusCode === 200) {
var oBearerToken = JSON.parse(response.contentAsString);
var bearerToken = oBearerToken.token;
return bearerToken;
}
}
}
// Main
if (
String(in_userName).trim() !== "" &&
String(in_password).trim() !== ""
) {
var fqdn = getFQDN();
if (fqdn !== null) {
var bearerToken = retrieveBearerToken(
"https://" + fqdn,
in_userName,
in_password
);
if (bearerToken !== null) {
System.log(bearerToken);
return bearerToken;
}
}
} else {
throw new Error(
"in_userName or in_password argument can not be null"
);
}
}
|