UNPKG

13.8 kBJavaScriptView Raw
1"use strict";
2var __assign = (this && this.__assign) || function () {
3 __assign = Object.assign || function(t) {
4 for (var s, i = 1, n = arguments.length; i < n; i++) {
5 s = arguments[i];
6 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7 t[p] = s[p];
8 }
9 return t;
10 };
11 return __assign.apply(this, arguments);
12};
13var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15 return new (P || (P = Promise))(function (resolve, reject) {
16 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19 step((generator = generator.apply(thisArg, _arguments || [])).next());
20 });
21};
22var __generator = (this && this.__generator) || function (thisArg, body) {
23 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25 function verb(n) { return function (v) { return step([n, v]); }; }
26 function step(op) {
27 if (f) throw new TypeError("Generator is already executing.");
28 while (_) try {
29 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;
30 if (y = 0, t) op = [op[0] & 2, t.value];
31 switch (op[0]) {
32 case 0: case 1: t = op; break;
33 case 4: _.label++; return { value: op[1], done: false };
34 case 5: _.label++; y = op[1]; op = [0]; continue;
35 case 7: op = _.ops.pop(); _.trys.pop(); continue;
36 default:
37 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41 if (t[2]) _.ops.pop();
42 _.trys.pop(); continue;
43 }
44 op = body.call(thisArg, _);
45 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47 }
48};
49var __importDefault = (this && this.__importDefault) || function (mod) {
50 return (mod && mod.__esModule) ? mod : { "default": mod };
51};
52var _a;
53Object.defineProperty(exports, "__esModule", { value: true });
54exports.headerForClientCredentials = exports.jwtBearerTokenGrant = exports.refreshTokenGrant = exports.userTokenGrant = exports.clientCredentialsGrant = void 0;
55var util_1 = require("@sap-cloud-sdk/util");
56var axios_1 = __importDefault(require("axios"));
57var opossum_1 = __importDefault(require("opossum"));
58var http_agent_1 = require("../../../http-agent");
59var resilience_options_1 = require("../resilience-options");
60var logger = (0, util_1.createLogger)({
61 package: 'core',
62 messageContext: 'xsuaa-service'
63});
64var circuitBreaker;
65/**
66 * @deprecated Since v1.49.0 Use `@sap/xssec` lib instead.
67 * Executes a client credentials grant request.
68 * If the first parameter is an instance of [[XsuaaServiceCredentials]], the response's access_token will be verified.
69 * If the first parameter is a URI, the response will not be verified.
70 * @param tokenServiceUrlOrXsuaaServiceCredentials - The URL of the token service or the credentials of a XSUAA service instance.
71 * @param clientCredentials - Client credentials for which to request a token.
72 * @param options - Options to use by retrieving access token.
73 * @param customBody - Object containing value required for the body request.
74 * @returns A promise resolving to the response.
75 */
76function clientCredentialsGrant(tokenServiceUrlOrXsuaaServiceCredentials, clientCredentials, options, customBody) {
77 if (customBody === void 0) { customBody = {}; }
78 return __awaiter(this, void 0, void 0, function () {
79 var authHeader, body, data, error_1;
80 return __generator(this, function (_a) {
81 switch (_a.label) {
82 case 0:
83 authHeader = headerForClientCredentials(clientCredentials);
84 body = __assign({ grant_type: GrantType.CLIENT_CREDENTIALS }, customBody);
85 _a.label = 1;
86 case 1:
87 _a.trys.push([1, 3, , 4]);
88 return [4 /*yield*/, post(tokenServiceUrlOrXsuaaServiceCredentials, authHeader, objectToXWwwUrlEncodedBodyString(body), options)];
89 case 2:
90 data = (_a.sent()).data;
91 return [2 /*return*/, data];
92 case 3:
93 error_1 = _a.sent();
94 throw accessTokenError(error_1, GrantType.CLIENT_CREDENTIALS);
95 case 4: return [2 /*return*/];
96 }
97 });
98 });
99}
100exports.clientCredentialsGrant = clientCredentialsGrant;
101/**
102 * @deprecated Since v1.41.0 Use [[jwtBearerTokenGrant]] instead.
103 * Executes a user token grant request against the given URI.
104 * @param tokenServiceUrlOrXsuaaServiceCredentials - The URL of the token service or the credentials of a XSUAA service instance.
105 * @param userJwt - The JWT of the user on whose behalf the request is executed.
106 * @param clientId - The client_id of the target XSUAA service instance.
107 * @param options - Options to use by retrieving access token
108 * @returns A promise resolving to the response of the XSUAA service.
109 */
110function userTokenGrant(tokenServiceUrlOrXsuaaServiceCredentials, userJwt, clientId, options) {
111 return __awaiter(this, void 0, void 0, function () {
112 var authHeader, body, data, error_2;
113 return __generator(this, function (_a) {
114 switch (_a.label) {
115 case 0:
116 authHeader = 'Bearer ' + userJwt;
117 body = objectToXWwwUrlEncodedBodyString({
118 client_id: clientId,
119 grant_type: GrantType.USER_TOKEN,
120 response_type: 'token'
121 });
122 _a.label = 1;
123 case 1:
124 _a.trys.push([1, 3, , 4]);
125 return [4 /*yield*/, post(tokenServiceUrlOrXsuaaServiceCredentials, authHeader, body, options)];
126 case 2:
127 data = (_a.sent()).data;
128 return [2 /*return*/, data];
129 case 3:
130 error_2 = _a.sent();
131 throw accessTokenError(error_2, GrantType.USER_TOKEN);
132 case 4: return [2 /*return*/];
133 }
134 });
135 });
136}
137exports.userTokenGrant = userTokenGrant;
138/**
139 * @deprecated Since v1.41.0 Use [[jwtBearerTokenGrant]] instead.
140 * Executes a refresh token grant request against the given URI.
141 * If the first parameter is an instance of [[XsuaaServiceCredentials]], the response's access_token will be verified.
142 * If the first parameter is an URI, the response will not be verified.
143 * @param tokenServiceUrlOrXsuaaServiceCredentials - The URL of the token service or the credentials of a XSUAA service instance.
144 * @param clientCredentials - The credentials (client_id, client_secret) of the target XSUAA service instance.
145 * @param refreshToken - The refresh token that should be used to generate a new access token.
146 * @param options - Options to use by retrieving access token.
147 * @returns A promise resolving to the response of the XSUAA service.
148 */
149function refreshTokenGrant(tokenServiceUrlOrXsuaaServiceCredentials, clientCredentials, refreshToken, options) {
150 return __awaiter(this, void 0, void 0, function () {
151 var authHeader, body, data, error_3;
152 return __generator(this, function (_a) {
153 switch (_a.label) {
154 case 0:
155 authHeader = headerForClientCredentials(clientCredentials);
156 body = objectToXWwwUrlEncodedBodyString({
157 grant_type: GrantType.REFRESH_TOKEN,
158 refresh_token: refreshToken
159 });
160 _a.label = 1;
161 case 1:
162 _a.trys.push([1, 3, , 4]);
163 return [4 /*yield*/, post(tokenServiceUrlOrXsuaaServiceCredentials, authHeader, body, options)];
164 case 2:
165 data = (_a.sent()).data;
166 return [2 /*return*/, data];
167 case 3:
168 error_3 = _a.sent();
169 throw accessTokenError(error_3, GrantType.REFRESH_TOKEN);
170 case 4: return [2 /*return*/];
171 }
172 });
173 });
174}
175exports.refreshTokenGrant = refreshTokenGrant;
176/**
177 * @deprecated Since v1.49.0 Use `@sap/xssec` lib instead.
178 * Executes a JWT bearer token grant request against the given URI.
179 * @param tokenServiceUrlOrXsuaaServiceCredentials - The URL of the token service or the credentials of a XSUAA service instance.
180 * @param clientCredentials - The credentials (client_id, client_secret) of the target XSUAA service instance.
181 * @param userJwt - The JWT of the user on whose behalf the request is executed.
182 * @param options - Options to use by retrieving access token.
183 * @returns A promise resolving to the response of the XSUAA service.
184 */
185function jwtBearerTokenGrant(tokenServiceUrlOrXsuaaServiceCredentials, clientCredentials, userJwt, options) {
186 return __awaiter(this, void 0, void 0, function () {
187 var authHeader, body, data, error_4;
188 return __generator(this, function (_a) {
189 switch (_a.label) {
190 case 0:
191 authHeader = headerForClientCredentials(clientCredentials);
192 body = objectToXWwwUrlEncodedBodyString({
193 client_id: clientCredentials.username,
194 assertion: userJwt,
195 grant_type: GrantType.JWT_BEARER_TOKEN,
196 response_type: 'token'
197 });
198 _a.label = 1;
199 case 1:
200 _a.trys.push([1, 3, , 4]);
201 return [4 /*yield*/, post(tokenServiceUrlOrXsuaaServiceCredentials, authHeader, body, options)];
202 case 2:
203 data = (_a.sent()).data;
204 return [2 /*return*/, data];
205 case 3:
206 error_4 = _a.sent();
207 throw accessTokenError(error_4, GrantType.JWT_BEARER_TOKEN);
208 case 4: return [2 /*return*/];
209 }
210 });
211 });
212}
213exports.jwtBearerTokenGrant = jwtBearerTokenGrant;
214function headers(authHeader) {
215 return {
216 headers: {
217 Authorization: authHeader,
218 'Content-Type': 'application/x-www-form-urlencoded',
219 Accept: 'application/json'
220 }
221 };
222}
223function post(tokenServiceUrlOrXsuaaServiceCredentials, authHeader, body, options) {
224 if (options === void 0) { options = { enableCircuitBreaker: true }; }
225 var targetUri = typeof tokenServiceUrlOrXsuaaServiceCredentials === 'string'
226 ? tokenServiceUrlOrXsuaaServiceCredentials
227 : getTokenServiceUrl(tokenServiceUrlOrXsuaaServiceCredentials);
228 var config = __assign(__assign(__assign({}, (0, http_agent_1.urlAndAgent)(targetUri)), { proxy: false, method: 'post', data: body }), headers(authHeader));
229 if (options.enableCircuitBreaker) {
230 return getCircuitBreaker().fire(config);
231 }
232 return axios_1.default.request(config);
233}
234function headerForClientCredentials(clientCredentials) {
235 return ('Basic ' +
236 (0, util_1.encodeBase64)("".concat(clientCredentials.username, ":").concat(clientCredentials.password)));
237}
238exports.headerForClientCredentials = headerForClientCredentials;
239function objectToXWwwUrlEncodedBodyString(bodyAsObject) {
240 return Object.entries(bodyAsObject)
241 .map(function (kv) { return kv.join('='); })
242 .join('&');
243}
244var GrantType;
245(function (GrantType) {
246 GrantType["USER_TOKEN"] = "user_token";
247 GrantType["REFRESH_TOKEN"] = "refresh_token";
248 GrantType["CLIENT_CREDENTIALS"] = "client_credentials";
249 GrantType["JWT_BEARER_TOKEN"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";
250})(GrantType || (GrantType = {}));
251function getTokenServiceUrl(xsuaaServiceCredentials) {
252 var xsuaaUri = xsuaaServiceCredentials.url.replace(/\/$/, '');
253 logger.info("Adding \"/oauth/token\" to the end of the target uri: ".concat(xsuaaUri, "."));
254 return "".concat(xsuaaUri, "/oauth/token");
255}
256function accessTokenError(error, grant) {
257 return new util_1.ErrorWithCause("FetchTokenError: ".concat(grantTypeMapper[grant], " Grant failed! ").concat(error.message), error);
258}
259function getCircuitBreaker() {
260 if (!circuitBreaker) {
261 circuitBreaker = new opossum_1.default(axios_1.default.request, resilience_options_1.circuitBreakerDefaultOptions);
262 }
263 return circuitBreaker;
264}
265var grantTypeMapper = (_a = {},
266 _a[GrantType.USER_TOKEN] = 'User token',
267 _a[GrantType.REFRESH_TOKEN] = 'Refresh token',
268 _a[GrantType.CLIENT_CREDENTIALS] = 'Client credentials',
269 _a[GrantType.JWT_BEARER_TOKEN] = 'JWT token',
270 _a);
271//# sourceMappingURL=xsuaa-service.js.map
\No newline at end of file