fabric-ias
Version:
Node.JS Service for Microsoft Fabric supporting infrastructure as code
70 lines (67 loc) • 2.66 kB
JavaScript
;
const axios = require("axios");
/**
* @class AzOauth
* @classdesc
* Handles OAuth authentication for Microsoft Fabric IAS API.
* Manages token retrieval, caching, and expiration.
*
* @property {string} _tenant_id - Azure tenant ID.
* @property {string} _client - Client application ID.
* @property {string} _secret - Client secret.
* @property {string} _token - Cached access token.
* @property {string|null} _expires - Expiration date/time for the token.
*/
class AzOauth {
/**
* Constructs an AzOauth instance with authentication options.
* @param {Object} options - OAuth configuration options.
* @param {string} options.tenant - Azure tenant ID.
* @param {string} options.client - Client application ID.
* @param {string} options.secret - Client secret.
* @param {string} [options.token] - Optional initial token.
* @param {string|null} [options.expires] - Optional initial token expiration.
*/
constructor(options) {
this._tenant_id = options.tenant || '';
this._client = options.client || '';
this._secret = options.secret || '';
this._token = options.token || '';
this._expires = options.expires || null;
}
/**
* Authenticates the client app and retrieves a bearer token from Microsoft.
* Caches the token and its expiration for reuse until expired.
*
* @returns {Promise<string|Error>} Bearer token string if successful.
* @throws {Error} If authentication fails or the token cannot be retrieved.
*/
async authorization() {
var currentDate = new Date();
if (this._expires == null || this._token == '' || new Date(this._expires) <= currentDate) {
const options = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
const form = {
grant_type: 'client_credentials',
scope: 'https://api.fabric.microsoft.com/.default',
client_id: this._client,
client_secret: this._secret
};
try {
const response = await axios.post(`https://login.microsoftonline.com/${this._tenant_id}/oauth2/v2.0/token`, form, options);
if (response.data.access_token == undefined || response.data.access_token == '') throw Error('Invalid Authorization: Failed to retrieve authorization');
var newDate = new Date();
newDate.setSeconds(newDate.getSeconds() + response.data.expires_in);
this._token = response.data.access_token;
this._expires = newDate.toISOString();
} catch (error) {
errorHandler(error);
}
}
return `Bearer ${this._token}`;
}
}
module.exports = AzOauth;