@appzmonster/msal-token-interceptor
Version:
Msal-Token-Interceptor is a request interceptor which uses Microsoft MSAL to handle OAuth 2.0 token exchange with Microsoft Identity Platform during a fetch request. This is part of fetch-interceptor family.
272 lines (207 loc) • 11.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MsalTokenHandler = void 0;
var _fetchInterceptor = require("@appzmonster/fetch-interceptor");
var _msalBrowser = require("@azure/msal-browser");
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var MsalTokenHandler = /*#__PURE__*/function (_BaseInterceptor) {
_inherits(MsalTokenHandler, _BaseInterceptor);
var _super = _createSuper(MsalTokenHandler);
function MsalTokenHandler(tokenRequest, msalInstance, setAccount) {
var _this;
_classCallCheck(this, MsalTokenHandler);
_this = _super.call(this);
_this._msalInstance = msalInstance;
_this._tokenRequest = tokenRequest;
_this._setAccount = setAccount;
var defaultValue = MsalTokenHandler.getDefault();
if (defaultValue != null) {
_this._defaultMsalInstance = defaultValue.msalInstance;
_this._defaultTokenRequest = defaultValue.tokenRequest;
}
_this._token = null;
return _this;
}
_createClass(MsalTokenHandler, [{
key: "invoke",
value: function () {
var _invoke = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee(resource, init) {
var authorizationHeader;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
// Reset the token before invoking a new token request.
this._token = null; // Exchange token with auth server.
_context.next = 3;
return this._acquireToken();
case 3:
this._token = _context.sent;
if (!(this._token != null && this._token.accessToken != null)) {
_context.next = 9;
break;
}
authorizationHeader = {
Authorization: "Bearer ".concat(this._token.accessToken)
};
init.headers = Object.assign({}, init.headers, authorizationHeader);
_context.next = 10;
break;
case 9:
throw new Error("Unable to exchange a valid token with authorization server");
case 10:
_context.next = 12;
return _get(_getPrototypeOf(MsalTokenHandler.prototype), "fetch", this).call(this, resource, init);
case 12:
return _context.abrupt("return", _context.sent);
case 13:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function invoke(_x, _x2) {
return _invoke.apply(this, arguments);
}
return invoke;
}()
}, {
key: "token",
value: function () {
var _token = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2() {
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
return _context2.abrupt("return", this._token);
case 1:
case "end":
return _context2.stop();
}
}
}, _callee2, this);
}));
function token() {
return _token.apply(this, arguments);
}
return token;
}()
}, {
key: "_getMsalInstance",
value: function _getMsalInstance() {
var msalInstance = null;
if (this._msalInstance != null) {
msalInstance = this._msalInstance;
} else {
msalInstance = this._defaultMsalInstance;
}
if (msalInstance == null) {
throw new Error('MSAL instance is missing from both default registration and current request');
}
return msalInstance;
}
}, {
key: "_acquireToken",
value: function () {
var _acquireToken2 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() {
var request, token;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
request = Object.assign({}, this._tokenRequest);
token = null;
if (request.account == null) {
request.account = this._getUserAccount();
} // Use registered default redirect uri (if any) if request does not set
// redirect uri. If no redirect uri is set at the request level, it will
// fallback using the redirect uri configured at msal instance level.
if ('redirectUri' in request === false) {
if (_typeof(this._defaultTokenRequest) === 'object' && typeof this._defaultTokenRequest.redirectUri === 'string') {
request.redirectUri = this._defaultTokenRequest.redirectUri;
}
} // If token is not found in the local cache or near expiration, msal will
// attempt to exchange a new token with the authorization server using a
// hidden iframe. Msal will cache the response token in local cache. Such
// flow is call silent authentication and is achieved via the authorization
// endpoint with 'prompt' query string set as 'none'.
console.log("request", request);
_context3.next = 7;
return this._getMsalInstance().acquireTokenSilent(request);
case 7:
token = _context3.sent;
if (!(token == null)) {
_context3.next = 10;
break;
}
throw new Error("Unable to exchange a valid token with authorization server");
case 10:
return _context3.abrupt("return", token);
case 11:
case "end":
return _context3.stop();
}
}
}, _callee3, this);
}));
function _acquireToken() {
return _acquireToken2.apply(this, arguments);
}
return _acquireToken;
}()
}, {
key: "_getUserAccount",
value: function _getUserAccount() {
var userAccount = null;
var userAccounts = this._getMsalInstance().getAllAccounts();
if (this._setAccount != null) {
userAccount = this._setAccount(userAccounts);
} else {
if (userAccounts != null && userAccounts instanceof Array && userAccounts.length > 0) {
userAccount = userAccounts[0];
}
}
return userAccount;
}
}]);
return MsalTokenHandler;
}(_fetchInterceptor.BaseInterceptor);
exports.MsalTokenHandler = MsalTokenHandler;
MsalTokenHandler.registerDefault = function (defaultMsalInstance, defaultTokenRequest) {
if ('fetch' in window === false) {
return;
}
if ('with' in window.fetch === false || typeof window.fetch["with"] !== 'function') {
console.error('Unable to register default MSAL token handler interceptor because @appzmonster/fetch-interceptor dependency is not found');
return;
}
var fetchManager = window.fetch["with"];
fetchManager._defaultMsalTokenHandler = {
msalInstance: defaultMsalInstance,
tokenRequest: defaultTokenRequest
};
};
MsalTokenHandler.getDefault = function () {
var defaultValue = null;
if ('fetch' in window && 'with' in window.fetch && _typeof(window.fetch["with"]._defaultMsalTokenHandler) === 'object') {
defaultValue = window.fetch["with"]._defaultMsalTokenHandler;
}
return defaultValue;
};