UNPKG

@sap-cloud-sdk/core

Version:
173 lines • 10.3 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; Object.defineProperty(exports, "__esModule", { value: true }); exports.jwtBearerToken = exports.userApprovedServiceToken = exports.serviceToken = void 0; var util_1 = require("@sap-cloud-sdk/util"); var jwt_1 = require("./jwt"); var client_credentials_token_cache_1 = require("./client-credentials-token-cache"); var environment_accessor_1 = require("./environment-accessor"); var subdomain_replacer_1 = require("./subdomain-replacer"); var xsuaa_service_1 = require("./legacy/xsuaa-service"); var xsuaa_service_2 = require("./xsuaa-service"); /** * Returns an access token that can be used to call the given service. The token is fetched via a client credentials grant with the credentials of the given service. * If multiple instances of the provided service exist, the first instance will be selected. * When a JWT is passed, the tenant of the JWT will be used when performing the grant. * When no JWT is passed, the grant will be performed using the provider tenant. * * Throws an error if there is no instance of the given service type or the XSUAA service, or if the request to the XSUAA service fails. * @param service - The type of the service or an instance of [[Service]]. * @param options - Options to influence caching and resilience behavior (see [[CachingOptions]] and [[ResilienceOptions]], respectively) and a JWT. By default, caching and usage of a circuit breaker are enabled. * @returns Access token. */ function serviceToken(service, options) { return __awaiter(this, void 0, void 0, function () { var opts, serviceCredentials, xsuaa, cachedToken, token, err_1; return __generator(this, function (_a) { switch (_a.label) { case 0: opts = __assign({ useCache: true, enableCircuitBreaker: true }, options); service = (0, environment_accessor_1.resolveService)(service); serviceCredentials = service.credentials; xsuaa = multiTenantXsuaaCredentials(options); if (opts.useCache) { cachedToken = client_credentials_token_cache_1.clientCredentialsTokenCache.getGrantTokenFromCache(xsuaa.url, serviceCredentials.clientid); if (cachedToken) { return [2 /*return*/, cachedToken.access_token]; } } _a.label = 1; case 1: _a.trys.push([1, 3, , 4]); return [4 /*yield*/, (0, xsuaa_service_2.getClientCredentialsToken)(service, options === null || options === void 0 ? void 0 : options.userJwt, options)]; case 2: token = _a.sent(); if (opts.useCache) { client_credentials_token_cache_1.clientCredentialsTokenCache.cacheRetrievedToken(xsuaa.url, serviceCredentials.clientid, token); } return [2 /*return*/, token.access_token]; case 3: err_1 = _a.sent(); throw new util_1.ErrorWithCause("Could not fetch client credentials token for service of type \"".concat(service.label, "\"."), err_1); case 4: return [2 /*return*/]; } }); }); } exports.serviceToken = serviceToken; /** * @deprecated Since v1.41.0 Use [[jwtBearerToken]] instead. * Returns a user approved access token that can be used to call the given service on behalf of the given user. The token is fetched via user token + refresh token grant. * This can be necessary for scenarios in which a token for a service is required, but the service needs * to know about the user on whose behalf the request is performed (for example to let the destination * service perform principal propagation with SAP S/4HANA Cloud). * * Throws an error if there is no instance of the given service type or the XSUAA service, or if the request to the XSUAA service fails. * @param userJwt - The JWT of the user for whom the access token should be fetched. * @param service - The type of the service or an instance of [[Service]]. * @param options - Options to influence resilience behavior (see [[ResilienceOptions]]). By default, usage of a circuit breaker is enabled. * @returns A user approved access token. */ function userApprovedServiceToken(userJwt, service, options) { return __awaiter(this, void 0, void 0, function () { var resolvedService, opts, xsuaa, serviceCreds; return __generator(this, function (_a) { resolvedService = (0, environment_accessor_1.resolveService)(service); opts = __assign({ enableCircuitBreaker: true }, options); xsuaa = multiTenantXsuaaCredentials({ userJwt: userJwt }); serviceCreds = (0, environment_accessor_1.extractClientCredentials)(resolvedService.credentials); return [2 /*return*/, (0, xsuaa_service_1.userTokenGrant)(xsuaa, userJwt, serviceCreds.username, opts) .then(function (userToken) { return (0, xsuaa_service_1.refreshTokenGrant)(xsuaa, serviceCreds, userToken.refresh_token, opts); }) .then(function (refreshToken) { return refreshToken.access_token; }) .catch(function (error) { throw new util_1.ErrorWithCause("Fetching a user approved access token for service \"".concat(resolvedService.label, "\" failed!"), error); })]; }); }); } exports.userApprovedServiceToken = userApprovedServiceToken; /** * Returns a jwt bearer token that can be used to call the given service. * The token is fetched via a JWT bearer token grant using the user token + client credentials. * * Throws an error if there is no instance of the given service type or the XSUAA service, or if the request to the XSUAA service fails. * @param userJwt - The JWT of the user for whom the access token should be fetched * @param service - The type of the service or an instance of [[Service]]. * @param options - Options to influence resilience behavior (see [[ResilienceOptions]]). By default, usage of a circuit breaker is enabled. * @returns A jwt bearer token. */ function jwtBearerToken(userJwt, service, options) { return __awaiter(this, void 0, void 0, function () { var resolvedService, opts; return __generator(this, function (_a) { resolvedService = (0, environment_accessor_1.resolveService)(service); opts = __assign({ enableCircuitBreaker: true }, options); return [2 /*return*/, (0, xsuaa_service_2.getUserToken)(resolvedService, userJwt, opts)]; }); }); } exports.jwtBearerToken = jwtBearerToken; function multiTenantXsuaaCredentials(options) { if (options === void 0) { options = {}; } var xsuaa = options.xsuaaCredentials ? __assign({}, options.xsuaaCredentials) : (0, environment_accessor_1.getXsuaaServiceCredentials)(options.userJwt); if (options.userJwt) { var decodedJwt = typeof options.userJwt === 'string' ? (0, jwt_1.decodeJwt)(options.userJwt) : options.userJwt; if (!decodedJwt.iss) { throw Error('Property `iss` is missing in the provided user token.'); } xsuaa.url = (0, subdomain_replacer_1.replaceSubdomain)(decodedJwt.iss, xsuaa.url); } return xsuaa; } //# sourceMappingURL=token-accessor.js.map