Commit 3a84cbd5 authored by Ahmet Turan Koçak's avatar Ahmet Turan Koçak
Browse files

Initial commit

parents
/*! @azure/msal-common v9.0.1 2022-12-07 */
'use strict';
import { __extends, __awaiter, __generator } from '../_virtual/_tslib.js';
import { BaseClient } from './BaseClient.js';
import { ClientAuthError } from '../error/ClientAuthError.js';
import { RequestParameterBuilder } from '../request/RequestParameterBuilder.js';
import { GrantType, Constants } from '../utils/Constants.js';
import { TimeUtils } from '../utils/TimeUtils.js';
import { ResponseHandler } from '../response/ResponseHandler.js';
import { StringUtils } from '../utils/StringUtils.js';
import { ServerError } from '../error/ServerError.js';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* OAuth2.0 Device code client
*/
var DeviceCodeClient = /** @class */ (function (_super) {
__extends(DeviceCodeClient, _super);
function DeviceCodeClient(configuration) {
return _super.call(this, configuration) || this;
}
/**
* Gets device code from device code endpoint, calls back to with device code response, and
* polls token endpoint to exchange device code for tokens
* @param request
*/
DeviceCodeClient.prototype.acquireToken = function (request) {
return __awaiter(this, void 0, void 0, function () {
var deviceCodeResponse, reqTimestamp, response, responseHandler;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this.getDeviceCode(request)];
case 1:
deviceCodeResponse = _a.sent();
request.deviceCodeCallback(deviceCodeResponse);
reqTimestamp = TimeUtils.nowSeconds();
return [4 /*yield*/, this.acquireTokenWithDeviceCode(request, deviceCodeResponse)];
case 2:
response = _a.sent();
responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
// Validate response. This function throws a server error if an error is returned by the server.
responseHandler.validateTokenResponse(response);
return [4 /*yield*/, responseHandler.handleServerTokenResponse(response, this.authority, reqTimestamp, request)];
case 3: return [2 /*return*/, _a.sent()];
}
});
});
};
/**
* Creates device code request and executes http GET
* @param request
*/
DeviceCodeClient.prototype.getDeviceCode = function (request) {
return __awaiter(this, void 0, void 0, function () {
var queryString, headers, thumbprint;
return __generator(this, function (_a) {
queryString = this.createQueryString(request);
headers = this.createTokenRequestHeaders();
thumbprint = {
clientId: this.config.authOptions.clientId,
authority: request.authority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid
};
return [2 /*return*/, this.executePostRequestToDeviceCodeEndpoint(this.authority.deviceCodeEndpoint, queryString, headers, thumbprint)];
});
});
};
/**
* Executes POST request to device code endpoint
* @param deviceCodeEndpoint
* @param queryString
* @param headers
*/
DeviceCodeClient.prototype.executePostRequestToDeviceCodeEndpoint = function (deviceCodeEndpoint, queryString, headers, thumbprint) {
return __awaiter(this, void 0, void 0, function () {
var _a, userCode, deviceCode, verificationUri, expiresIn, interval, message;
return __generator(this, function (_b) {
switch (_b.label) {
case 0: return [4 /*yield*/, this.networkManager.sendPostRequest(thumbprint, deviceCodeEndpoint, {
body: queryString,
headers: headers,
proxyUrl: this.config.systemOptions.proxyUrl
})];
case 1:
_a = (_b.sent()).body, userCode = _a.user_code, deviceCode = _a.device_code, verificationUri = _a.verification_uri, expiresIn = _a.expires_in, interval = _a.interval, message = _a.message;
return [2 /*return*/, {
userCode: userCode,
deviceCode: deviceCode,
verificationUri: verificationUri,
expiresIn: expiresIn,
interval: interval,
message: message
}];
}
});
});
};
/**
* Create device code endpoint query parameters and returns string
*/
DeviceCodeClient.prototype.createQueryString = function (request) {
var parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addScopes(request.scopes);
parameterBuilder.addClientId(this.config.authOptions.clientId);
if (!StringUtils.isEmpty(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
return parameterBuilder.createQueryString();
};
/**
* Breaks the polling with specific conditions.
* @param request CommonDeviceCodeRequest
* @param deviceCodeResponse DeviceCodeResponse
*/
DeviceCodeClient.prototype.continuePolling = function (deviceCodeExpirationTime, userSpecifiedTimeout, userSpecifiedCancelFlag) {
if (userSpecifiedCancelFlag) {
this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true");
throw ClientAuthError.createDeviceCodeCancelledError();
}
else if (userSpecifiedTimeout && userSpecifiedTimeout < deviceCodeExpirationTime && TimeUtils.nowSeconds() > userSpecifiedTimeout) {
this.logger.error("User defined timeout for device code polling reached. The timeout was set for " + userSpecifiedTimeout);
throw ClientAuthError.createUserTimeoutReachedError();
}
else if (TimeUtils.nowSeconds() > deviceCodeExpirationTime) {
if (userSpecifiedTimeout) {
this.logger.verbose("User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for " + userSpecifiedTimeout);
}
this.logger.error("Device code expired. Expiration time of device code was " + deviceCodeExpirationTime);
throw ClientAuthError.createDeviceCodeExpiredError();
}
return true;
};
/**
* Creates token request with device code response and polls token endpoint at interval set by the device code
* response
* @param request
* @param deviceCodeResponse
*/
DeviceCodeClient.prototype.acquireTokenWithDeviceCode = function (request, deviceCodeResponse) {
return __awaiter(this, void 0, void 0, function () {
var requestBody, headers, userSpecifiedTimeout, deviceCodeExpirationTime, pollingIntervalMilli, thumbprint, response;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
requestBody = this.createTokenRequestBody(request, deviceCodeResponse);
headers = this.createTokenRequestHeaders();
userSpecifiedTimeout = request.timeout ? TimeUtils.nowSeconds() + request.timeout : undefined;
deviceCodeExpirationTime = TimeUtils.nowSeconds() + deviceCodeResponse.expiresIn;
pollingIntervalMilli = deviceCodeResponse.interval * 1000;
_a.label = 1;
case 1:
if (!this.continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, request.cancel)) return [3 /*break*/, 8];
thumbprint = {
clientId: this.config.authOptions.clientId,
authority: request.authority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid
};
return [4 /*yield*/, this.executePostToTokenEndpoint(this.authority.tokenEndpoint, requestBody, headers, thumbprint)];
case 2:
response = _a.sent();
if (!(response.body && response.body.error)) return [3 /*break*/, 6];
if (!(response.body.error === Constants.AUTHORIZATION_PENDING)) return [3 /*break*/, 4];
this.logger.info("Authorization pending. Continue polling.");
return [4 /*yield*/, TimeUtils.delay(pollingIntervalMilli)];
case 3:
_a.sent();
return [3 /*break*/, 5];
case 4:
// for any other error, throw
this.logger.info("Unexpected error in polling from the server");
throw ServerError.createPostRequestFailed(response.body.error);
case 5: return [3 /*break*/, 7];
case 6:
this.logger.verbose("Authorization completed successfully. Polling stopped.");
return [2 /*return*/, response.body];
case 7: return [3 /*break*/, 1];
case 8:
/*
* The above code should've thrown by this point, but to satisfy TypeScript,
* and in the rare case the conditionals in continuePolling() may not catch everything...
*/
this.logger.error("Polling stopped for unknown reasons.");
throw ClientAuthError.createDeviceCodeUnknownError();
}
});
});
};
/**
* Creates query parameters and converts to string.
* @param request
* @param deviceCodeResponse
*/
DeviceCodeClient.prototype.createTokenRequestBody = function (request, deviceCodeResponse) {
var requestParameters = new RequestParameterBuilder();
requestParameters.addScopes(request.scopes);
requestParameters.addClientId(this.config.authOptions.clientId);
requestParameters.addGrantType(GrantType.DEVICE_CODE_GRANT);
requestParameters.addDeviceCode(deviceCodeResponse.deviceCode);
var correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
requestParameters.addCorrelationId(correlationId);
requestParameters.addClientInfo();
requestParameters.addLibraryInfo(this.config.libraryInfo);
requestParameters.addApplicationTelemetry(this.config.telemetry.application);
requestParameters.addThrottling();
if (this.serverTelemetryManager) {
requestParameters.addServerTelemetry(this.serverTelemetryManager);
}
if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
requestParameters.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
return requestParameters.createQueryString();
};
return DeviceCodeClient;
}(BaseClient));
export { DeviceCodeClient };
//# sourceMappingURL=DeviceCodeClient.js.map
{"version":3,"file":"DeviceCodeClient.js","sources":["../../src/client/DeviceCodeClient.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { DeviceCodeResponse, ServerDeviceCodeResponse } from \"../response/DeviceCodeResponse\";\nimport { BaseClient } from \"./BaseClient\";\nimport { CommonDeviceCodeRequest } from \"../request/CommonDeviceCodeRequest\";\nimport { ClientAuthError } from \"../error/ClientAuthError\";\nimport { RequestParameterBuilder } from \"../request/RequestParameterBuilder\";\nimport { Constants, GrantType } from \"../utils/Constants\";\nimport { ClientConfiguration } from \"../config/ClientConfiguration\";\nimport { TimeUtils } from \"../utils/TimeUtils\";\nimport { ServerAuthorizationTokenResponse } from \"../response/ServerAuthorizationTokenResponse\";\nimport { ResponseHandler } from \"../response/ResponseHandler\";\nimport { AuthenticationResult } from \"../response/AuthenticationResult\";\nimport { StringUtils } from \"../utils/StringUtils\";\nimport { RequestThumbprint } from \"../network/RequestThumbprint\";\nimport { ServerError } from \"../error/ServerError\";\n\n/**\n * OAuth2.0 Device code client\n */\nexport class DeviceCodeClient extends BaseClient {\n\n constructor(configuration: ClientConfiguration) {\n super(configuration);\n }\n\n /**\n * Gets device code from device code endpoint, calls back to with device code response, and\n * polls token endpoint to exchange device code for tokens\n * @param request\n */\n public async acquireToken(request: CommonDeviceCodeRequest): Promise<AuthenticationResult | null> {\n const deviceCodeResponse: DeviceCodeResponse = await this.getDeviceCode(request);\n request.deviceCodeCallback(deviceCodeResponse);\n const reqTimestamp = TimeUtils.nowSeconds();\n const response: ServerAuthorizationTokenResponse = await this.acquireTokenWithDeviceCode(\n request,\n deviceCodeResponse);\n\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n this.config.serializableCache,\n this.config.persistencePlugin\n );\n\n // Validate response. This function throws a server error if an error is returned by the server.\n responseHandler.validateTokenResponse(response);\n return await responseHandler.handleServerTokenResponse(\n response,\n this.authority,\n reqTimestamp,\n request\n );\n }\n\n /**\n * Creates device code request and executes http GET\n * @param request\n */\n private async getDeviceCode(request: CommonDeviceCodeRequest): Promise<DeviceCodeResponse> {\n const queryString = this.createQueryString(request);\n const headers = this.createTokenRequestHeaders();\n const thumbprint: RequestThumbprint = {\n clientId: this.config.authOptions.clientId,\n authority: request.authority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid\n };\n\n return this.executePostRequestToDeviceCodeEndpoint(this.authority.deviceCodeEndpoint, queryString, headers, thumbprint);\n }\n\n /**\n * Executes POST request to device code endpoint\n * @param deviceCodeEndpoint\n * @param queryString\n * @param headers\n */\n private async executePostRequestToDeviceCodeEndpoint(\n deviceCodeEndpoint: string,\n queryString: string,\n headers: Record<string, string>,\n thumbprint: RequestThumbprint): Promise<DeviceCodeResponse> {\n\n const {\n body: {\n user_code: userCode,\n device_code: deviceCode,\n verification_uri: verificationUri,\n expires_in: expiresIn,\n interval,\n message\n }\n } = await this.networkManager.sendPostRequest<ServerDeviceCodeResponse>(\n thumbprint,\n deviceCodeEndpoint,\n {\n body: queryString,\n headers: headers,\n proxyUrl: this.config.systemOptions.proxyUrl\n });\n\n return {\n userCode,\n deviceCode,\n verificationUri,\n expiresIn,\n interval,\n message\n };\n }\n\n /**\n * Create device code endpoint query parameters and returns string\n */\n private createQueryString(request: CommonDeviceCodeRequest): string {\n\n const parameterBuilder: RequestParameterBuilder = new RequestParameterBuilder();\n\n parameterBuilder.addScopes(request.scopes);\n parameterBuilder.addClientId(this.config.authOptions.clientId);\n\n if (!StringUtils.isEmpty(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {\n parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);\n }\n\n return parameterBuilder.createQueryString();\n }\n\n /**\n * Breaks the polling with specific conditions.\n * @param request CommonDeviceCodeRequest\n * @param deviceCodeResponse DeviceCodeResponse\n */\n private continuePolling(\n deviceCodeExpirationTime: number,\n userSpecifiedTimeout?: number,\n userSpecifiedCancelFlag?: boolean,\n ): boolean {\n if (userSpecifiedCancelFlag) {\n this.logger.error(\"Token request cancelled by setting DeviceCodeRequest.cancel = true\");\n throw ClientAuthError.createDeviceCodeCancelledError();\n } else if (userSpecifiedTimeout && userSpecifiedTimeout < deviceCodeExpirationTime && TimeUtils.nowSeconds() > userSpecifiedTimeout) {\n this.logger.error(`User defined timeout for device code polling reached. The timeout was set for ${userSpecifiedTimeout}`);\n throw ClientAuthError.createUserTimeoutReachedError();\n } else if (TimeUtils.nowSeconds() > deviceCodeExpirationTime) {\n if (userSpecifiedTimeout) {\n this.logger.verbose(`User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${userSpecifiedTimeout}`);\n }\n this.logger.error(`Device code expired. Expiration time of device code was ${deviceCodeExpirationTime}`);\n throw ClientAuthError.createDeviceCodeExpiredError();\n }\n return true;\n }\n\n /**\n * Creates token request with device code response and polls token endpoint at interval set by the device code\n * response\n * @param request\n * @param deviceCodeResponse\n */\n private async acquireTokenWithDeviceCode(\n request: CommonDeviceCodeRequest,\n deviceCodeResponse: DeviceCodeResponse): Promise<ServerAuthorizationTokenResponse> {\n\n const requestBody = this.createTokenRequestBody(request, deviceCodeResponse);\n const headers: Record<string, string> = this.createTokenRequestHeaders();\n\n const userSpecifiedTimeout = request.timeout ? TimeUtils.nowSeconds() + request.timeout : undefined;\n const deviceCodeExpirationTime = TimeUtils.nowSeconds() + deviceCodeResponse.expiresIn;\n const pollingIntervalMilli = deviceCodeResponse.interval * 1000;\n\n /*\n * Poll token endpoint while (device code is not expired AND operation has not been cancelled by\n * setting CancellationToken.cancel = true). POST request is sent at interval set by pollingIntervalMilli\n */\n while (this.continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, request.cancel)) {\n const thumbprint: RequestThumbprint = {\n clientId: this.config.authOptions.clientId,\n authority: request.authority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid\n };\n\n const response = await this.executePostToTokenEndpoint(\n this.authority.tokenEndpoint,\n requestBody,\n headers,\n thumbprint);\n\n if (response.body && response.body.error) {\n // user authorization is pending. Sleep for polling interval and try again\n if(response.body.error === Constants.AUTHORIZATION_PENDING) {\n this.logger.info(\"Authorization pending. Continue polling.\");\n await TimeUtils.delay(pollingIntervalMilli);\n } else {\n // for any other error, throw\n this.logger.info(\"Unexpected error in polling from the server\");\n throw ServerError.createPostRequestFailed(response.body.error);\n }\n } else {\n this.logger.verbose(\"Authorization completed successfully. Polling stopped.\");\n return response.body;\n }\n }\n\n /*\n * The above code should've thrown by this point, but to satisfy TypeScript,\n * and in the rare case the conditionals in continuePolling() may not catch everything...\n */\n this.logger.error(\"Polling stopped for unknown reasons.\");\n throw ClientAuthError.createDeviceCodeUnknownError();\n }\n\n /**\n * Creates query parameters and converts to string.\n * @param request\n * @param deviceCodeResponse\n */\n private createTokenRequestBody(request: CommonDeviceCodeRequest, deviceCodeResponse: DeviceCodeResponse): string {\n\n const requestParameters: RequestParameterBuilder = new RequestParameterBuilder();\n\n requestParameters.addScopes(request.scopes);\n requestParameters.addClientId(this.config.authOptions.clientId);\n requestParameters.addGrantType(GrantType.DEVICE_CODE_GRANT);\n requestParameters.addDeviceCode(deviceCodeResponse.deviceCode);\n const correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();\n requestParameters.addCorrelationId(correlationId);\n requestParameters.addClientInfo();\n requestParameters.addLibraryInfo(this.config.libraryInfo);\n requestParameters.addApplicationTelemetry(this.config.telemetry.application);\n requestParameters.addThrottling();\n \n if (this.serverTelemetryManager) {\n requestParameters.addServerTelemetry(this.serverTelemetryManager);\n }\n\n if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {\n requestParameters.addClaims(request.claims, this.config.authOptions.clientCapabilities);\n }\n return requestParameters.createQueryString();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;AAGG;AAiBH;;AAEG;AACH,IAAA,gBAAA,kBAAA,UAAA,MAAA,EAAA;IAAsC,SAAU,CAAA,gBAAA,EAAA,MAAA,CAAA,CAAA;AAE5C,IAAA,SAAA,gBAAA,CAAY,aAAkC,EAAA;AAC1C,QAAA,OAAA,MAAA,CAAA,IAAA,CAAA,IAAA,EAAM,aAAa,CAAC,IAAA,IAAA,CAAA;KACvB;AAED;;;;AAIG;IACU,gBAAY,CAAA,SAAA,CAAA,YAAA,GAAzB,UAA0B,OAAgC,EAAA;;;;;AACP,oBAAA,KAAA,CAAA,EAAA,OAAA,CAAA,CAAA,YAAM,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,CAAA,CAAA;;AAA1E,wBAAA,kBAAkB,GAAuB,EAAiC,CAAA,IAAA,EAAA,CAAA;AAChF,wBAAA,OAAO,CAAC,kBAAkB,CAAC,kBAAkB,CAAC,CAAC;AACzC,wBAAA,YAAY,GAAG,SAAS,CAAC,UAAU,EAAE,CAAC;wBACO,OAAM,CAAA,CAAA,YAAA,IAAI,CAAC,0BAA0B,CACpF,OAAO,EACP,kBAAkB,CAAC,CAAA,CAAA;;AAFjB,wBAAA,QAAQ,GAAqC,EAE5B,CAAA,IAAA,EAAA,CAAA;AAEjB,wBAAA,eAAe,GAAG,IAAI,eAAe,CACvC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,QAAQ,EAChC,IAAI,CAAC,YAAY,EACjB,IAAI,CAAC,WAAW,EAChB,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,MAAM,CAAC,iBAAiB,EAC7B,IAAI,C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BAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAM1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAW7E;;GAEG;AACH,qBAAa,gBAAiB,SAAQ,UAAU;IAE5C,OAAO,CAAC,QAAQ,CAAW;IAC3B,OAAO,CAAC,iBAAiB,CAAS;gBAEtB,aAAa,EAAE,mBAAmB;IAI9C;;;OAGG;IACU,YAAY,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IAkBjG;;;;;;;OAOG;YACW,6BAA6B;IAsD3C;;;;OAIG;IACH,OAAO,CAAC,0BAA0B;IAmBlC;;;;;OAKG;IACH,OAAO,CAAC,8BAA8B;IAgCtC;;;;OAIG;YACW,mBAAmB;IA0CjC;;;OAGG;IACH,OAAO,CAAC,sBAAsB;CAsCjC"}
\ No newline at end of file
/*! @azure/msal-common v9.0.1 2022-12-07 */
'use strict';
import { __extends, __awaiter, __generator } from '../_virtual/_tslib.js';
import { BaseClient } from './BaseClient.js';
import { RequestParameterBuilder } from '../request/RequestParameterBuilder.js';
import { ScopeSet } from '../request/ScopeSet.js';
import { AuthenticationScheme, CredentialType, GrantType, AADServerParamKeys, CacheOutcome, Constants } from '../utils/Constants.js';
import { ResponseHandler } from '../response/ResponseHandler.js';
import { TimeUtils } from '../utils/TimeUtils.js';
import { AuthToken } from '../account/AuthToken.js';
import { ClientAuthError } from '../error/ClientAuthError.js';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* On-Behalf-Of client
*/
var OnBehalfOfClient = /** @class */ (function (_super) {
__extends(OnBehalfOfClient, _super);
function OnBehalfOfClient(configuration) {
return _super.call(this, configuration) || this;
}
/**
* Public API to acquire tokens with on behalf of flow
* @param request
*/
OnBehalfOfClient.prototype.acquireToken = function (request) {
return __awaiter(this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
this.scopeSet = new ScopeSet(request.scopes || []);
// generate the user_assertion_hash for OBOAssertion
_a = this;
return [4 /*yield*/, this.cryptoUtils.hashString(request.oboAssertion)];
case 1:
// generate the user_assertion_hash for OBOAssertion
_a.userAssertionHash = _b.sent();
if (!request.skipCache) return [3 /*break*/, 3];
return [4 /*yield*/, this.executeTokenRequest(request, this.authority, this.userAssertionHash)];
case 2: return [2 /*return*/, _b.sent()];
case 3:
_b.trys.push([3, 5, , 7]);
return [4 /*yield*/, this.getCachedAuthenticationResult(request)];
case 4: return [2 /*return*/, _b.sent()];
case 5:
_b.sent();
return [4 /*yield*/, this.executeTokenRequest(request, this.authority, this.userAssertionHash)];
case 6:
// Any failure falls back to interactive request, once we implement distributed cache, we plan to handle `createRefreshRequiredError` to refresh using the RT
return [2 /*return*/, _b.sent()];
case 7: return [2 /*return*/];
}
});
});
};
/**
* look up cache for tokens
* Find idtoken in the cache
* Find accessToken based on user assertion and account info in the cache
* Please note we are not yet supported OBO tokens refreshed with long lived RT. User will have to send a new assertion if the current access token expires
* This is to prevent security issues when the assertion changes over time, however, longlived RT helps retaining the session
* @param request
*/
OnBehalfOfClient.prototype.getCachedAuthenticationResult = function (request) {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var cachedAccessToken, cachedIdToken, idTokenObject, cachedAccount, localAccountId, accountInfo;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
cachedAccessToken = this.readAccessTokenFromCacheForOBO(this.config.authOptions.clientId, request);
if (!cachedAccessToken) {
// Must refresh due to non-existent access_token.
(_a = this.serverTelemetryManager) === null || _a === void 0 ? void 0 : _a.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);
this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.");
throw ClientAuthError.createRefreshRequiredError();
}
else if (TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
// Access token expired, will need to renewed
(_b = this.serverTelemetryManager) === null || _b === void 0 ? void 0 : _b.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
this.logger.info("OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within " + this.config.systemOptions.tokenRenewalOffsetSeconds + " seconds.");
throw ClientAuthError.createRefreshRequiredError();
}
cachedIdToken = this.readIdTokenFromCacheForOBO(request, cachedAccessToken.homeAccountId);
cachedAccount = null;
if (cachedIdToken) {
idTokenObject = new AuthToken(cachedIdToken.secret, this.config.cryptoInterface);
localAccountId = idTokenObject.claims.oid ? idTokenObject.claims.oid : idTokenObject.claims.sub;
accountInfo = {
homeAccountId: cachedIdToken.homeAccountId,
environment: cachedIdToken.environment,
tenantId: cachedIdToken.realm,
username: Constants.EMPTY_STRING,
localAccountId: localAccountId || Constants.EMPTY_STRING
};
cachedAccount = this.cacheManager.readAccountFromCache(accountInfo);
}
// increment telemetry cache hit counter
if (this.config.serverTelemetryManager) {
this.config.serverTelemetryManager.incrementCacheHits();
}
return [4 /*yield*/, ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, {
account: cachedAccount,
accessToken: cachedAccessToken,
idToken: cachedIdToken,
refreshToken: null,
appMetadata: null
}, true, request, idTokenObject)];
case 1: return [2 /*return*/, _c.sent()];
}
});
});
};
/**
* read idtoken from cache, this is a specific implementation for OBO as the requirements differ from a generic lookup in the cacheManager
* Certain use cases of OBO flow do not expect an idToken in the cache/or from the service
* @param request
*/
OnBehalfOfClient.prototype.readIdTokenFromCacheForOBO = function (request, atHomeAccountId) {
var idTokenFilter = {
homeAccountId: atHomeAccountId,
environment: this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,
credentialType: CredentialType.ID_TOKEN,
clientId: this.config.authOptions.clientId,
realm: this.authority.tenant
};
var credentialCache = this.cacheManager.getCredentialsFilteredBy(idTokenFilter);
var idTokens = Object.keys(credentialCache.idTokens).map(function (key) { return credentialCache.idTokens[key]; });
// When acquiring a token on behalf of an application, there might not be an id token in the cache
if (idTokens.length < 1) {
return null;
}
return idTokens[0];
};
/**
* Fetches the cached access token based on incoming assertion
* @param clientId
* @param request
* @param userAssertionHash
*/
OnBehalfOfClient.prototype.readAccessTokenFromCacheForOBO = function (clientId, request) {
var authScheme = request.authenticationScheme || AuthenticationScheme.BEARER;
/*
* Distinguish between Bearer and PoP/SSH token cache types
* Cast to lowercase to handle "bearer" from ADFS
*/
var credentialType = (authScheme && authScheme.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase()) ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME : CredentialType.ACCESS_TOKEN;
var accessTokenFilter = {
credentialType: credentialType,
clientId: clientId,
target: this.scopeSet.printScopesLowerCase(),
tokenType: authScheme,
keyId: request.sshKid,
requestedClaimsHash: request.requestedClaimsHash,
userAssertionHash: this.userAssertionHash
};
var credentialCache = this.cacheManager.getCredentialsFilteredBy(accessTokenFilter);
var accessTokens = Object.keys(credentialCache.accessTokens).map(function (key) { return credentialCache.accessTokens[key]; });
var numAccessTokens = accessTokens.length;
if (numAccessTokens < 1) {
return null;
}
else if (numAccessTokens > 1) {
throw ClientAuthError.createMultipleMatchingTokensInCacheError();
}
return accessTokens[0];
};
/**
* Make a network call to the server requesting credentials
* @param request
* @param authority
*/
OnBehalfOfClient.prototype.executeTokenRequest = function (request, authority, userAssertionHash) {
return __awaiter(this, void 0, void 0, function () {
var requestBody, headers, thumbprint, reqTimestamp, response, responseHandler, tokenResponse;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
requestBody = this.createTokenRequestBody(request);
headers = this.createTokenRequestHeaders();
thumbprint = {
clientId: this.config.authOptions.clientId,
authority: request.authority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid
};
reqTimestamp = TimeUtils.nowSeconds();
return [4 /*yield*/, this.executePostToTokenEndpoint(authority.tokenEndpoint, requestBody, headers, thumbprint)];
case 1:
response = _a.sent();
responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
responseHandler.validateTokenResponse(response.body);
return [4 /*yield*/, responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, undefined, userAssertionHash)];
case 2:
tokenResponse = _a.sent();
return [2 /*return*/, tokenResponse];
}
});
});
};
/**
* generate a server request in accepable format
* @param request
*/
OnBehalfOfClient.prototype.createTokenRequestBody = function (request) {
var parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(this.config.authOptions.clientId);
parameterBuilder.addScopes(request.scopes);
parameterBuilder.addGrantType(GrantType.JWT_BEARER);
parameterBuilder.addClientInfo();
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
var correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
parameterBuilder.addCorrelationId(correlationId);
parameterBuilder.addRequestTokenUse(AADServerParamKeys.ON_BEHALF_OF);
parameterBuilder.addOboAssertion(request.oboAssertion);
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
var clientAssertion = this.config.clientCredentials.clientAssertion;
parameterBuilder.addClientAssertion(clientAssertion.assertion);
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
return parameterBuilder.createQueryString();
};
return OnBehalfOfClient;
}(BaseClient));
export { OnBehalfOfClient };
//# sourceMappingURL=OnBehalfOfClient.js.map
{"version":3,"file":"OnBehalfOfClient.js","sources":["../../src/client/OnBehalfOfClient.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ClientConfiguration } from \"../config/ClientConfiguration\";\nimport { BaseClient } from \"./BaseClient\";\nimport { Authority } from \"../authority/Authority\";\nimport { RequestParameterBuilder } from \"../request/RequestParameterBuilder\";\nimport { ScopeSet } from \"../request/ScopeSet\";\nimport { GrantType, AADServerParamKeys , CredentialType, Constants, CacheOutcome, AuthenticationScheme } from \"../utils/Constants\";\nimport { ResponseHandler } from \"../response/ResponseHandler\";\nimport { AuthenticationResult } from \"../response/AuthenticationResult\";\nimport { CommonOnBehalfOfRequest } from \"../request/CommonOnBehalfOfRequest\";\nimport { TimeUtils } from \"../utils/TimeUtils\";\nimport { CredentialFilter, CredentialCache } from \"../cache/utils/CacheTypes\";\nimport { AccessTokenEntity } from \"../cache/entities/AccessTokenEntity\";\nimport { IdTokenEntity } from \"../cache/entities/IdTokenEntity\";\nimport { AccountEntity } from \"../cache/entities/AccountEntity\";\nimport { AuthToken } from \"../account/AuthToken\";\nimport { ClientAuthError } from \"../error/ClientAuthError\";\nimport { RequestThumbprint } from \"../network/RequestThumbprint\";\nimport { AccountInfo } from \"../account/AccountInfo\";\n\n/**\n * On-Behalf-Of client\n */\nexport class OnBehalfOfClient extends BaseClient {\n\n private scopeSet: ScopeSet;\n private userAssertionHash: string;\n\n constructor(configuration: ClientConfiguration) {\n super(configuration);\n }\n\n /**\n * Public API to acquire tokens with on behalf of flow\n * @param request\n */\n public async acquireToken(request: CommonOnBehalfOfRequest): Promise<AuthenticationResult | null> {\n this.scopeSet = new ScopeSet(request.scopes || []);\n\n // generate the user_assertion_hash for OBOAssertion\n this.userAssertionHash = await this.cryptoUtils.hashString(request.oboAssertion);\n\n if (request.skipCache) {\n return await this.executeTokenRequest(request, this.authority, this.userAssertionHash);\n }\n\n try {\n return await this.getCachedAuthenticationResult(request);\n } catch (e) {\n // Any failure falls back to interactive request, once we implement distributed cache, we plan to handle `createRefreshRequiredError` to refresh using the RT\n return await this.executeTokenRequest(request, this.authority, this.userAssertionHash);\n }\n }\n\n /**\n * look up cache for tokens\n * Find idtoken in the cache\n * Find accessToken based on user assertion and account info in the cache\n * Please note we are not yet supported OBO tokens refreshed with long lived RT. User will have to send a new assertion if the current access token expires\n * This is to prevent security issues when the assertion changes over time, however, longlived RT helps retaining the session\n * @param request\n */\n private async getCachedAuthenticationResult(request: CommonOnBehalfOfRequest): Promise<AuthenticationResult | null> {\n\n // look in the cache for the access_token which matches the incoming_assertion\n const cachedAccessToken = this.readAccessTokenFromCacheForOBO(this.config.authOptions.clientId, request);\n if (!cachedAccessToken) {\n // Must refresh due to non-existent access_token.\n this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);\n this.logger.info(\"SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.\");\n throw ClientAuthError.createRefreshRequiredError();\n } else if (TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {\n // Access token expired, will need to renewed\n this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);\n this.logger.info(`OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`);\n throw ClientAuthError.createRefreshRequiredError();\n }\n\n // fetch the idToken from cache\n const cachedIdToken = this.readIdTokenFromCacheForOBO(request, cachedAccessToken.homeAccountId);\n let idTokenObject: AuthToken | undefined;\n let cachedAccount: AccountEntity | null = null;\n if (cachedIdToken) {\n idTokenObject = new AuthToken(cachedIdToken.secret, this.config.cryptoInterface);\n const localAccountId = idTokenObject.claims.oid ? idTokenObject.claims.oid : idTokenObject.claims.sub;\n const accountInfo: AccountInfo = {\n homeAccountId: cachedIdToken.homeAccountId,\n environment: cachedIdToken.environment,\n tenantId: cachedIdToken.realm,\n username: Constants.EMPTY_STRING,\n localAccountId: localAccountId || Constants.EMPTY_STRING\n };\n\n cachedAccount = this.cacheManager.readAccountFromCache(accountInfo);\n }\n\n // increment telemetry cache hit counter\n if (this.config.serverTelemetryManager) {\n this.config.serverTelemetryManager.incrementCacheHits();\n }\n\n return await ResponseHandler.generateAuthenticationResult(\n this.cryptoUtils,\n this.authority,\n {\n account: cachedAccount,\n accessToken: cachedAccessToken,\n idToken: cachedIdToken,\n refreshToken: null,\n appMetadata: null\n },\n true,\n request,\n idTokenObject);\n }\n\n /**\n * read idtoken from cache, this is a specific implementation for OBO as the requirements differ from a generic lookup in the cacheManager\n * Certain use cases of OBO flow do not expect an idToken in the cache/or from the service\n * @param request\n */\n private readIdTokenFromCacheForOBO(request: CommonOnBehalfOfRequest, atHomeAccountId: string): IdTokenEntity | null {\n\n const idTokenFilter: CredentialFilter = {\n homeAccountId: atHomeAccountId,\n environment: this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,\n credentialType: CredentialType.ID_TOKEN,\n clientId: this.config.authOptions.clientId,\n realm: this.authority.tenant\n };\n\n const credentialCache: CredentialCache = this.cacheManager.getCredentialsFilteredBy(idTokenFilter);\n const idTokens = Object.keys(credentialCache.idTokens).map(key => credentialCache.idTokens[key]);\n // When acquiring a token on behalf of an application, there might not be an id token in the cache\n if (idTokens.length < 1) {\n return null;\n }\n return idTokens[0] as IdTokenEntity;\n }\n\n /**\n * Fetches the cached access token based on incoming assertion\n * @param clientId\n * @param request\n * @param userAssertionHash\n */\n private readAccessTokenFromCacheForOBO(clientId: string, request: CommonOnBehalfOfRequest) {\n const authScheme = request.authenticationScheme || AuthenticationScheme.BEARER;\n /*\n * Distinguish between Bearer and PoP/SSH token cache types\n * Cast to lowercase to handle \"bearer\" from ADFS\n */\n const credentialType = (authScheme && authScheme.toLowerCase() !== AuthenticationScheme.BEARER.toLowerCase()) ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME : CredentialType.ACCESS_TOKEN;\n\n const accessTokenFilter: CredentialFilter = {\n credentialType: credentialType,\n clientId,\n target: this.scopeSet.printScopesLowerCase(),\n tokenType: authScheme,\n keyId: request.sshKid,\n requestedClaimsHash: request.requestedClaimsHash,\n userAssertionHash: this.userAssertionHash\n };\n\n const credentialCache: CredentialCache = this.cacheManager.getCredentialsFilteredBy(accessTokenFilter);\n\n const accessTokens = Object.keys(credentialCache.accessTokens).map((key) => credentialCache.accessTokens[key]);\n\n const numAccessTokens = accessTokens.length;\n if (numAccessTokens < 1) {\n return null;\n } else if (numAccessTokens > 1) {\n throw ClientAuthError.createMultipleMatchingTokensInCacheError();\n }\n\n return accessTokens[0] as AccessTokenEntity;\n }\n\n /**\n * Make a network call to the server requesting credentials\n * @param request\n * @param authority\n */\n private async executeTokenRequest(request: CommonOnBehalfOfRequest, authority: Authority, userAssertionHash: string)\n : Promise<AuthenticationResult | null> {\n\n const requestBody = this.createTokenRequestBody(request);\n const headers: Record<string, string> = this.createTokenRequestHeaders();\n const thumbprint: RequestThumbprint = {\n clientId: this.config.authOptions.clientId,\n authority: request.authority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid\n };\n\n const reqTimestamp = TimeUtils.nowSeconds();\n const response = await this.executePostToTokenEndpoint(authority.tokenEndpoint, requestBody, headers, thumbprint);\n\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n this.config.serializableCache,\n this.config.persistencePlugin\n );\n\n responseHandler.validateTokenResponse(response.body);\n const tokenResponse = await responseHandler.handleServerTokenResponse(\n response.body,\n this.authority,\n reqTimestamp,\n request,\n undefined,\n userAssertionHash\n );\n\n return tokenResponse;\n }\n\n /**\n * generate a server request in accepable format\n * @param request\n */\n private createTokenRequestBody(request: CommonOnBehalfOfRequest): string {\n const parameterBuilder = new RequestParameterBuilder();\n\n parameterBuilder.addClientId(this.config.authOptions.clientId);\n\n parameterBuilder.addScopes(request.scopes);\n\n parameterBuilder.addGrantType(GrantType.JWT_BEARER);\n\n parameterBuilder.addClientInfo();\n\n parameterBuilder.addLibraryInfo(this.config.libraryInfo);\n parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);\n parameterBuilder.addThrottling();\n\n if (this.serverTelemetryManager) {\n parameterBuilder.addServerTelemetry(this.serverTelemetryManager);\n }\n\n const correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();\n parameterBuilder.addCorrelationId(correlationId);\n\n parameterBuilder.addRequestTokenUse(AADServerParamKeys.ON_BEHALF_OF);\n\n parameterBuilder.addOboAssertion(request.oboAssertion);\n\n if (this.config.clientCredentials.clientSecret) {\n parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);\n }\n\n if (this.config.clientCredentials.clientAssertion) {\n const clientAssertion = this.config.clientCredentials.clientAssertion;\n parameterBuilder.addClientAssertion(clientAssertion.assertion);\n parameterBuilder.addClientAssertionType(clientAssertion.assertionType);\n }\n\n return parameterBuilder.createQueryString();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;AAGG;AAqBH;;AAEG;AACH,IAAA,gBAAA,kBAAA,UAAA,MAAA,EAAA;IAAsC,SAAU,CAAA,gBAAA,EAAA,MAAA,CAAA,CAAA;AAK5C,IAAA,SAAA,gBAAA,CAAY,aAAkC,EAAA;AAC1C,QAAA,OAAA,MAAA,CAAA,IAAA,CAAA,IAAA,EAAM,aAAa,CAAC,IAAA,IAAA,CAAA;KACvB;AAED;;;AAGG;IACU,gBAAY,CAAA,SAAA,CAAA,YAAA,GAAzB,UAA0B,OAAgC,EAAA;;;;;;AACtD,wBAAA,IAAI,CAAC,QAAQ,GAAG,IAAI,QAAQ,CAAC,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;;AAGnD,wBAAA,EAAA,GAAA,IAAI,CAAA;wBAAqB,OAAM,CAAA,CAAA,YAAA,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,OAAO,CAAC,YAAY,CAAC,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AE,MAAM,sCAAsC,CAAC;AAMjF,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AAKxE,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAU7E,OAAO,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AACjF;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,UAAU;gBAClC,aAAa,EAAE,mBAAmB,EAAE,iBAAiB,CAAC,EAAE,kBAAkB;IAIzE,YAAY,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAkD5F;;;OAGG;IACU,0BAA0B,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAoCxG;;;OAGG;YACW,kCAAkC;IA6BhD;;;;OAIG;YACW,mBAAmB;IAkCjC;;;OAGG;IACH,OAAO,CAAC,0BAA0B;IAUlC;;;OAGG;YACW,sBAAsB;CA2EvC"}
\ No newline at end of file
/*! @azure/msal-common v9.0.1 2022-12-07 */
'use strict';
import { __extends, __awaiter, __generator, __assign } from '../_virtual/_tslib.js';
import { BaseClient } from './BaseClient.js';
import { RequestParameterBuilder } from '../request/RequestParameterBuilder.js';
import { AuthenticationScheme, GrantType, HeaderNames, Errors } from '../utils/Constants.js';
import { ResponseHandler } from '../response/ResponseHandler.js';
import { PopTokenGenerator } from '../crypto/PopTokenGenerator.js';
import { StringUtils } from '../utils/StringUtils.js';
import { ClientConfigurationError } from '../error/ClientConfigurationError.js';
import { ClientAuthError } from '../error/ClientAuthError.js';
import { ServerError } from '../error/ServerError.js';
import { TimeUtils } from '../utils/TimeUtils.js';
import { UrlString } from '../url/UrlString.js';
import { CcsCredentialType } from '../account/CcsCredential.js';
import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.js';
import { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage } from '../error/InteractionRequiredAuthError.js';
import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.js';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* OAuth2.0 refresh token client
*/
var RefreshTokenClient = /** @class */ (function (_super) {
__extends(RefreshTokenClient, _super);
function RefreshTokenClient(configuration, performanceClient) {
return _super.call(this, configuration, performanceClient) || this;
}
RefreshTokenClient.prototype.acquireToken = function (request) {
var _a, _b, _c;
return __awaiter(this, void 0, void 0, function () {
var atsMeasurement, reqTimestamp, response, requestId, responseHandler;
var _this = this;
return __generator(this, function (_d) {
switch (_d.label) {
case 0:
atsMeasurement = (_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.startMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
this.logger.verbose("RefreshTokenClientAcquireToken called", request.correlationId);
reqTimestamp = TimeUtils.nowSeconds();
return [4 /*yield*/, this.executeTokenRequest(request, this.authority)];
case 1:
response = _d.sent();
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.addStaticFields({
refreshTokenSize: ((_b = response.body.refresh_token) === null || _b === void 0 ? void 0 : _b.length) || 0
});
requestId = (_c = response.headers) === null || _c === void 0 ? void 0 : _c[HeaderNames.X_MS_REQUEST_ID];
responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
responseHandler.validateTokenResponse(response.body);
return [2 /*return*/, responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, undefined, undefined, true, request.forceCache, requestId).then(function (result) {
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.endMeasurement({
success: true
});
return result;
})
.catch(function (error) {
_this.logger.verbose("Error in fetching refresh token", request.correlationId);
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.endMeasurement({
errorCode: error.errorCode,
subErrorCode: error.subError,
success: false
});
throw error;
})];
}
});
});
};
/**
* Gets cached refresh token and attaches to request, then calls acquireToken API
* @param request
*/
RefreshTokenClient.prototype.acquireTokenByRefreshToken = function (request) {
return __awaiter(this, void 0, void 0, function () {
var isFOCI, noFamilyRTInCache, clientMismatchErrorWithFamilyRT;
return __generator(this, function (_a) {
// Cannot renew token if no request object is given.
if (!request) {
throw ClientConfigurationError.createEmptyTokenRequestError();
}
// We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
if (!request.account) {
throw ClientAuthError.createNoAccountInSilentRequestError();
}
isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment, this.config.authOptions.clientId);
// if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest
if (isFOCI) {
try {
return [2 /*return*/, this.acquireTokenWithCachedRefreshToken(request, true)];
}
catch (e) {
noFamilyRTInCache = e instanceof InteractionRequiredAuthError && e.errorCode === InteractionRequiredAuthErrorMessage.noTokensFoundError.code;
clientMismatchErrorWithFamilyRT = e instanceof ServerError && e.errorCode === Errors.INVALID_GRANT_ERROR && e.subError === Errors.CLIENT_MISMATCH_ERROR;
// if family Refresh Token (FRT) cache acquisition fails or if client_mismatch error is seen with FRT, reattempt with application Refresh Token (ART)
if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) {
return [2 /*return*/, this.acquireTokenWithCachedRefreshToken(request, false)];
// throw in all other cases
}
else {
throw e;
}
}
}
// fall back to application refresh token acquisition
return [2 /*return*/, this.acquireTokenWithCachedRefreshToken(request, false)];
});
});
};
/**
* makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached
* @param request
*/
RefreshTokenClient.prototype.acquireTokenWithCachedRefreshToken = function (request, foci) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var atsMeasurement, refreshToken, refreshTokenRequest;
return __generator(this, function (_b) {
atsMeasurement = (_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.startMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
this.logger.verbose("RefreshTokenClientAcquireTokenWithCachedRefreshToken called", request.correlationId);
refreshToken = this.cacheManager.readRefreshTokenFromCache(this.config.authOptions.clientId, request.account, foci);
if (!refreshToken) {
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.discardMeasurement();
throw InteractionRequiredAuthError.createNoTokensFoundError();
}
// attach cached RT size to the current measurement
atsMeasurement === null || atsMeasurement === void 0 ? void 0 : atsMeasurement.endMeasurement({
success: true
});
refreshTokenRequest = __assign(__assign({}, request), { refreshToken: refreshToken.secret, authenticationScheme: request.authenticationScheme || AuthenticationScheme.BEARER, ccsCredential: {
credential: request.account.homeAccountId,
type: CcsCredentialType.HOME_ACCOUNT_ID
} });
return [2 /*return*/, this.acquireToken(refreshTokenRequest)];
});
});
};
/**
* Constructs the network message and makes a NW call to the underlying secure token service
* @param request
* @param authority
*/
RefreshTokenClient.prototype.executeTokenRequest = function (request, authority) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var acquireTokenMeasurement, requestBody, queryParameters, headers, thumbprint, endpoint;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
acquireTokenMeasurement = (_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.startMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
return [4 /*yield*/, this.createTokenRequestBody(request)];
case 1:
requestBody = _b.sent();
queryParameters = this.createTokenQueryParameters(request);
headers = this.createTokenRequestHeaders(request.ccsCredential);
thumbprint = {
clientId: this.config.authOptions.clientId,
authority: authority.canonicalAuthority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid
};
endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParameters);
return [2 /*return*/, this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint)
.then(function (result) {
acquireTokenMeasurement === null || acquireTokenMeasurement === void 0 ? void 0 : acquireTokenMeasurement.endMeasurement({
success: true
});
return result;
})
.catch(function (error) {
acquireTokenMeasurement === null || acquireTokenMeasurement === void 0 ? void 0 : acquireTokenMeasurement.endMeasurement({
success: false
});
throw error;
})];
}
});
});
};
/**
* Creates query string for the /token request
* @param request
*/
RefreshTokenClient.prototype.createTokenQueryParameters = function (request) {
var parameterBuilder = new RequestParameterBuilder();
if (request.tokenQueryParameters) {
parameterBuilder.addExtraQueryParameters(request.tokenQueryParameters);
}
return parameterBuilder.createQueryString();
};
/**
* Helper function to create the token request body
* @param request
*/
RefreshTokenClient.prototype.createTokenRequestBody = function (request) {
var _a;
return __awaiter(this, void 0, void 0, function () {
var correlationId, acquireTokenMeasurement, parameterBuilder, clientAssertion, popTokenGenerator, reqCnfData, clientInfo;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
correlationId = request.correlationId;
acquireTokenMeasurement = (_a = this.performanceClient) === null || _a === void 0 ? void 0 : _a.startMeasurement(PerformanceEvents.BaseClientCreateTokenRequestHeaders, correlationId);
parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(this.config.authOptions.clientId);
parameterBuilder.addScopes(request.scopes);
parameterBuilder.addGrantType(GrantType.REFRESH_TOKEN_GRANT);
parameterBuilder.addClientInfo();
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
parameterBuilder.addCorrelationId(correlationId);
parameterBuilder.addRefreshToken(request.refreshToken);
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
clientAssertion = this.config.clientCredentials.clientAssertion;
parameterBuilder.addClientAssertion(clientAssertion.assertion);
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
if (!(request.authenticationScheme === AuthenticationScheme.POP)) return [3 /*break*/, 2];
popTokenGenerator = new PopTokenGenerator(this.cryptoUtils);
return [4 /*yield*/, popTokenGenerator.generateCnf(request)];
case 1:
reqCnfData = _b.sent();
// SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
parameterBuilder.addPopToken(reqCnfData.reqCnfString);
return [3 /*break*/, 3];
case 2:
if (request.authenticationScheme === AuthenticationScheme.SSH) {
if (request.sshJwk) {
parameterBuilder.addSshJwk(request.sshJwk);
}
else {
acquireTokenMeasurement === null || acquireTokenMeasurement === void 0 ? void 0 : acquireTokenMeasurement.endMeasurement({
success: false
});
throw ClientConfigurationError.createMissingSshJwkError();
}
}
_b.label = 3;
case 3:
if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
if (this.config.systemOptions.preventCorsPreflight && request.ccsCredential) {
switch (request.ccsCredential.type) {
case CcsCredentialType.HOME_ACCOUNT_ID:
try {
clientInfo = buildClientInfoFromHomeAccountId(request.ccsCredential.credential);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("Could not parse home account ID for CCS Header: " + e);
}
break;
case CcsCredentialType.UPN:
parameterBuilder.addCcsUpn(request.ccsCredential.credential);
break;
}
}
acquireTokenMeasurement === null || acquireTokenMeasurement === void 0 ? void 0 : acquireTokenMeasurement.endMeasurement({
success: true
});
return [2 /*return*/, parameterBuilder.createQueryString()];
}
});
});
};
return RefreshTokenClient;
}(BaseClient));
export { RefreshTokenClient };
//# sourceMappingURL=RefreshTokenClient.js.map
{"version":3,"file":"RefreshTokenClient.js","sources":["../../src/client/RefreshTokenClient.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { ClientConfiguration } from \"../config/ClientConfiguration\";\nimport { BaseClient } from \"./BaseClient\";\nimport { CommonRefreshTokenRequest } from \"../request/CommonRefreshTokenRequest\";\nimport { Authority } from \"../authority/Authority\";\nimport { ServerAuthorizationTokenResponse } from \"../response/ServerAuthorizationTokenResponse\";\nimport { RequestParameterBuilder } from \"../request/RequestParameterBuilder\";\nimport { GrantType, AuthenticationScheme, Errors, HeaderNames } from \"../utils/Constants\";\nimport { ResponseHandler } from \"../response/ResponseHandler\";\nimport { AuthenticationResult } from \"../response/AuthenticationResult\";\nimport { PopTokenGenerator } from \"../crypto/PopTokenGenerator\";\nimport { StringUtils } from \"../utils/StringUtils\";\nimport { RequestThumbprint } from \"../network/RequestThumbprint\";\nimport { NetworkResponse } from \"../network/NetworkManager\";\nimport { CommonSilentFlowRequest } from \"../request/CommonSilentFlowRequest\";\nimport { ClientConfigurationError } from \"../error/ClientConfigurationError\";\nimport { ClientAuthError } from \"../error/ClientAuthError\";\nimport { ServerError } from \"../error/ServerError\";\nimport { TimeUtils } from \"../utils/TimeUtils\";\nimport { UrlString } from \"../url/UrlString\";\nimport { CcsCredentialType } from \"../account/CcsCredential\";\nimport { buildClientInfoFromHomeAccountId } from \"../account/ClientInfo\";\nimport { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage } from \"../error/InteractionRequiredAuthError\";\nimport { PerformanceEvents } from \"../telemetry/performance/PerformanceEvent\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\n/**\n * OAuth2.0 refresh token client\n */\nexport class RefreshTokenClient extends BaseClient {\n constructor(configuration: ClientConfiguration, performanceClient?: IPerformanceClient) {\n super(configuration, performanceClient);\n\n }\n public async acquireToken(request: CommonRefreshTokenRequest): Promise<AuthenticationResult> {\n const atsMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);\n this.logger.verbose(\"RefreshTokenClientAcquireToken called\", request.correlationId);\n const reqTimestamp = TimeUtils.nowSeconds();\n const response = await this.executeTokenRequest(request, this.authority);\n atsMeasurement?.addStaticFields({\n refreshTokenSize: response.body.refresh_token?.length || 0\n });\n\n // Retrieve requestId from response headers\n const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];\n\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n this.config.serializableCache,\n this.config.persistencePlugin\n );\n\n responseHandler.validateTokenResponse(response.body);\n\n return responseHandler.handleServerTokenResponse(\n response.body,\n this.authority,\n reqTimestamp,\n request,\n undefined,\n undefined,\n true,\n request.forceCache,\n requestId\n ).then((result: AuthenticationResult) => {\n atsMeasurement?.endMeasurement({\n success: true\n });\n return result;\n })\n .catch((error) => {\n this.logger.verbose(\"Error in fetching refresh token\", request.correlationId);\n atsMeasurement?.endMeasurement({\n errorCode: error.errorCode,\n subErrorCode: error.subError,\n success: false\n });\n throw error;\n });\n }\n\n /**\n * Gets cached refresh token and attaches to request, then calls acquireToken API\n * @param request\n */\n public async acquireTokenByRefreshToken(request: CommonSilentFlowRequest): Promise<AuthenticationResult> {\n // Cannot renew token if no request object is given.\n if (!request) {\n throw ClientConfigurationError.createEmptyTokenRequestError();\n }\n\n // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases\n if (!request.account) {\n throw ClientAuthError.createNoAccountInSilentRequestError();\n }\n\n // try checking if FOCI is enabled for the given application\n const isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment, this.config.authOptions.clientId);\n\n // if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest\n if (isFOCI) {\n try {\n return this.acquireTokenWithCachedRefreshToken(request, true);\n } catch (e) {\n const noFamilyRTInCache = e instanceof InteractionRequiredAuthError && e.errorCode === InteractionRequiredAuthErrorMessage.noTokensFoundError.code;\n const clientMismatchErrorWithFamilyRT = e instanceof ServerError && e.errorCode === Errors.INVALID_GRANT_ERROR && e.subError === Errors.CLIENT_MISMATCH_ERROR;\n\n // if family Refresh Token (FRT) cache acquisition fails or if client_mismatch error is seen with FRT, reattempt with application Refresh Token (ART)\n if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) {\n return this.acquireTokenWithCachedRefreshToken(request, false);\n // throw in all other cases\n } else {\n throw e;\n }\n }\n }\n // fall back to application refresh token acquisition\n return this.acquireTokenWithCachedRefreshToken(request, false);\n\n }\n\n /**\n * makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached\n * @param request\n */\n private async acquireTokenWithCachedRefreshToken(request: CommonSilentFlowRequest, foci: boolean) {\n // fetches family RT or application RT based on FOCI value\n\n const atsMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);\n this.logger.verbose(\"RefreshTokenClientAcquireTokenWithCachedRefreshToken called\", request.correlationId);\n const refreshToken = this.cacheManager.readRefreshTokenFromCache(this.config.authOptions.clientId, request.account, foci);\n\n if (!refreshToken) {\n atsMeasurement?.discardMeasurement();\n throw InteractionRequiredAuthError.createNoTokensFoundError();\n }\n // attach cached RT size to the current measurement\n atsMeasurement?.endMeasurement({\n success: true\n });\n\n const refreshTokenRequest: CommonRefreshTokenRequest = {\n ...request,\n refreshToken: refreshToken.secret,\n authenticationScheme: request.authenticationScheme || AuthenticationScheme.BEARER,\n ccsCredential: {\n credential: request.account.homeAccountId,\n type: CcsCredentialType.HOME_ACCOUNT_ID\n }\n };\n\n return this.acquireToken(refreshTokenRequest);\n }\n\n /**\n * Constructs the network message and makes a NW call to the underlying secure token service\n * @param request\n * @param authority\n */\n private async executeTokenRequest(request: CommonRefreshTokenRequest, authority: Authority)\n : Promise<NetworkResponse<ServerAuthorizationTokenResponse>> {\n const acquireTokenMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);\n const requestBody = await this.createTokenRequestBody(request);\n const queryParameters = this.createTokenQueryParameters(request);\n const headers: Record<string, string> = this.createTokenRequestHeaders(request.ccsCredential);\n const thumbprint: RequestThumbprint = {\n clientId: this.config.authOptions.clientId,\n authority: authority.canonicalAuthority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid\n };\n\n const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParameters);\n return this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint)\n .then((result) => {\n acquireTokenMeasurement?.endMeasurement({\n success: true\n });\n return result;\n })\n .catch((error) => {\n acquireTokenMeasurement?.endMeasurement({\n success: false\n });\n throw error;\n });\n }\n\n /**\n * Creates query string for the /token request\n * @param request\n */\n private createTokenQueryParameters(request: CommonRefreshTokenRequest): string {\n const parameterBuilder = new RequestParameterBuilder();\n\n if (request.tokenQueryParameters) {\n parameterBuilder.addExtraQueryParameters(request.tokenQueryParameters);\n }\n\n return parameterBuilder.createQueryString();\n }\n\n /**\n * Helper function to create the token request body\n * @param request\n */\n private async createTokenRequestBody(request: CommonRefreshTokenRequest): Promise<string> {\n const correlationId = request.correlationId;\n const acquireTokenMeasurement = this.performanceClient?.startMeasurement(PerformanceEvents.BaseClientCreateTokenRequestHeaders, correlationId);\n const parameterBuilder = new RequestParameterBuilder();\n\n parameterBuilder.addClientId(this.config.authOptions.clientId);\n\n parameterBuilder.addScopes(request.scopes);\n\n parameterBuilder.addGrantType(GrantType.REFRESH_TOKEN_GRANT);\n\n parameterBuilder.addClientInfo();\n\n parameterBuilder.addLibraryInfo(this.config.libraryInfo);\n parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);\n parameterBuilder.addThrottling();\n\n if (this.serverTelemetryManager) {\n parameterBuilder.addServerTelemetry(this.serverTelemetryManager);\n }\n\n parameterBuilder.addCorrelationId(correlationId);\n\n parameterBuilder.addRefreshToken(request.refreshToken);\n\n if (this.config.clientCredentials.clientSecret) {\n parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);\n }\n\n if (this.config.clientCredentials.clientAssertion) {\n const clientAssertion = this.config.clientCredentials.clientAssertion;\n parameterBuilder.addClientAssertion(clientAssertion.assertion);\n parameterBuilder.addClientAssertionType(clientAssertion.assertionType);\n }\n\n if (request.authenticationScheme === AuthenticationScheme.POP) {\n const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils);\n const reqCnfData = await popTokenGenerator.generateCnf(request);\n // SPA PoP requires full Base64Url encoded req_cnf string (unhashed)\n parameterBuilder.addPopToken(reqCnfData.reqCnfString);\n } else if (request.authenticationScheme === AuthenticationScheme.SSH) {\n if (request.sshJwk) {\n parameterBuilder.addSshJwk(request.sshJwk);\n } else {\n acquireTokenMeasurement?.endMeasurement({\n success: false\n });\n throw ClientConfigurationError.createMissingSshJwkError();\n }\n }\n\n if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {\n parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);\n }\n\n if (this.config.systemOptions.preventCorsPreflight && request.ccsCredential) {\n switch (request.ccsCredential.type) {\n case CcsCredentialType.HOME_ACCOUNT_ID:\n try {\n const clientInfo = buildClientInfoFromHomeAccountId(request.ccsCredential.credential);\n parameterBuilder.addCcsOid(clientInfo);\n } catch (e) {\n this.logger.verbose(\"Could not parse home account ID for CCS Header: \" + e);\n }\n break;\n case CcsCredentialType.UPN:\n parameterBuilder.addCcsUpn(request.ccsCredential.credential);\n break;\n }\n }\n acquireTokenMeasurement?.endMeasurement({\n success: true\n });\n return parameterBuilder.createQueryString();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAAA;;;AAGG;AA0BH;;AAEG;AACH,IAAA,kBAAA,kBAAA,UAAA,MAAA,EAAA;IAAwC,SAAU,CAAA,kBAAA,EAAA,MAAA,CAAA,CAAA;IAC9C,SAAY,kBAAA,CAAA,aAAkC,EAAE,iBAAsC,EAAA;eAClF,MAAM,CAAA,IAAA,CAAA,IAAA,EAAA,aAAa,EAAE,iBAAiB,CAAC,IAAA,IAAA,CAAA;KAE1C;IACY,kBAAY,CAAA,SAAA,CAAA,YAAA,GAAzB,UAA0B,OAAkC,EAAA;;;;;;;;AAClD,wBAAA,cAAc,GAA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oCACtB,gBAAgB,CAAC,SAAS,CAAC,OAAO,CAAC,aAAa,CAAC,UAAU,CAAC,CAAC;oCAC7D,MAAM;AACb,6BAAA;AACJ,yBAAA;AACD,wBAAA,uBAAuB,aAAvB,uBAAuB,KAAA,KAAA,CAAA,GAAA,KAAA,CAAA,GAAvB,uBAAuB,CAAE,cAAc,CAAC;AACpC,4BAAA,OAAO,EAAE,IAAI;yBAChB,CAAE,CAAA;AACH,wBAAA,OAAA,CAAA,CAAA,aAAO,gBAAgB,CAAC,iBAAiB,EAAE,CAAC,CAAA;;;;AAC/C,KAAA,CAAA;IACL,OAAC,kBAAA,CAAA;AAAD,CApQA,CAAwC,UAAU,CAoQjD;;;;"}
\ No newline at end of file
{"version":3,"file":"SilentFlowClient.d.ts","sourceRoot":"","sources":["../../src/client/SilentFlowClient.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AASxE,OAAO,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AAEjF,qBAAa,gBAAiB,SAAQ,UAAU;gBAEhC,aAAa,EAAE,mBAAmB,EAAE,iBAAiB,CAAC,EAAE,kBAAkB;IAItF;;;;OAIG;IACG,YAAY,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAanF;;;OAGG;IACG,kBAAkB,CAAC,OAAO,EAAE,uBAAuB,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAiDzF;;;OAGG;YACW,6BAA6B;CAyB9C"}
\ No newline at end of file
/*! @azure/msal-common v9.0.1 2022-12-07 */
'use strict';
import { __extends, __awaiter, __generator } from '../_virtual/_tslib.js';
import { BaseClient } from './BaseClient.js';
import { AuthToken } from '../account/AuthToken.js';
import { TimeUtils } from '../utils/TimeUtils.js';
import { RefreshTokenClient } from './RefreshTokenClient.js';
import { ClientAuthError, ClientAuthErrorMessage } from '../error/ClientAuthError.js';
import { ClientConfigurationError } from '../error/ClientConfigurationError.js';
import { ResponseHandler } from '../response/ResponseHandler.js';
import { CacheOutcome } from '../utils/Constants.js';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
var SilentFlowClient = /** @class */ (function (_super) {
__extends(SilentFlowClient, _super);
function SilentFlowClient(configuration, performanceClient) {
return _super.call(this, configuration, performanceClient) || this;
}
/**
* Retrieves a token from cache if it is still valid, or uses the cached refresh token to renew
* the given token and returns the renewed token
* @param request
*/
SilentFlowClient.prototype.acquireToken = function (request) {
return __awaiter(this, void 0, void 0, function () {
var e_1, refreshTokenClient;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, this.acquireCachedToken(request)];
case 1: return [2 /*return*/, _a.sent()];
case 2:
e_1 = _a.sent();
if (e_1 instanceof ClientAuthError && e_1.errorCode === ClientAuthErrorMessage.tokenRefreshRequired.code) {
refreshTokenClient = new RefreshTokenClient(this.config, this.performanceClient);
return [2 /*return*/, refreshTokenClient.acquireTokenByRefreshToken(request)];
}
else {
throw e_1;
}
case 3: return [2 /*return*/];
}
});
});
};
/**
* Retrieves token from cache or throws an error if it must be refreshed.
* @param request
*/
SilentFlowClient.prototype.acquireCachedToken = function (request) {
var _a, _b, _c, _d;
return __awaiter(this, void 0, void 0, function () {
var environment, cacheRecord;
return __generator(this, function (_e) {
switch (_e.label) {
case 0:
// Cannot renew token if no request object is given.
if (!request) {
throw ClientConfigurationError.createEmptyTokenRequestError();
}
if (request.forceRefresh) {
// Must refresh due to present force_refresh flag.
(_a = this.serverTelemetryManager) === null || _a === void 0 ? void 0 : _a.setCacheOutcome(CacheOutcome.FORCE_REFRESH);
this.logger.info("SilentFlowClient:acquireCachedToken - Skipping cache because forceRefresh is true.");
throw ClientAuthError.createRefreshRequiredError();
}
// We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
if (!request.account) {
throw ClientAuthError.createNoAccountInSilentRequestError();
}
environment = request.authority || this.authority.getPreferredCache();
cacheRecord = this.cacheManager.readCacheRecord(request.account, this.config.authOptions.clientId, request, environment);
if (!cacheRecord.accessToken) {
// Must refresh due to non-existent access_token.
(_b = this.serverTelemetryManager) === null || _b === void 0 ? void 0 : _b.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);
this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.");
throw ClientAuthError.createRefreshRequiredError();
}
else if (TimeUtils.wasClockTurnedBack(cacheRecord.accessToken.cachedAt) ||
TimeUtils.isTokenExpired(cacheRecord.accessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
// Must refresh due to expired access_token.
(_c = this.serverTelemetryManager) === null || _c === void 0 ? void 0 : _c.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);
this.logger.info("SilentFlowClient:acquireCachedToken - Cached access token is expired or will expire within " + this.config.systemOptions.tokenRenewalOffsetSeconds + " seconds.");
throw ClientAuthError.createRefreshRequiredError();
}
else if (cacheRecord.accessToken.refreshOn && TimeUtils.isTokenExpired(cacheRecord.accessToken.refreshOn, 0)) {
// Must refresh due to the refresh_in value.
(_d = this.serverTelemetryManager) === null || _d === void 0 ? void 0 : _d.setCacheOutcome(CacheOutcome.REFRESH_CACHED_ACCESS_TOKEN);
this.logger.info("SilentFlowClient:acquireCachedToken - Cached access token's refreshOn property has been exceeded'.");
throw ClientAuthError.createRefreshRequiredError();
}
if (this.config.serverTelemetryManager) {
this.config.serverTelemetryManager.incrementCacheHits();
}
return [4 /*yield*/, this.generateResultFromCacheRecord(cacheRecord, request)];
case 1: return [2 /*return*/, _e.sent()];
}
});
});
};
/**
* Helper function to build response object from the CacheRecord
* @param cacheRecord
*/
SilentFlowClient.prototype.generateResultFromCacheRecord = function (cacheRecord, request) {
return __awaiter(this, void 0, void 0, function () {
var idTokenObj, authTime;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (cacheRecord.idToken) {
idTokenObj = new AuthToken(cacheRecord.idToken.secret, this.config.cryptoInterface);
}
// token max_age check
if (request.maxAge || (request.maxAge === 0)) {
authTime = idTokenObj === null || idTokenObj === void 0 ? void 0 : idTokenObj.claims.auth_time;
if (!authTime) {
throw ClientAuthError.createAuthTimeNotFoundError();
}
AuthToken.checkMaxAge(authTime, request.maxAge);
}
return [4 /*yield*/, ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, idTokenObj)];
case 1: return [2 /*return*/, _a.sent()];
}
});
});
};
return SilentFlowClient;
}(BaseClient));
export { SilentFlowClient };
//# sourceMappingURL=SilentFlowClient.js.map
{"version":3,"file":"SilentFlowClient.js","sources":["../../src/client/SilentFlowClient.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { BaseClient } from \"./BaseClient\";\nimport { ClientConfiguration } from \"../config/ClientConfiguration\";\nimport { CommonSilentFlowRequest } from \"../request/CommonSilentFlowRequest\";\nimport { AuthenticationResult } from \"../response/AuthenticationResult\";\nimport { AuthToken } from \"../account/AuthToken\";\nimport { TimeUtils } from \"../utils/TimeUtils\";\nimport { RefreshTokenClient } from \"./RefreshTokenClient\";\nimport { ClientAuthError, ClientAuthErrorMessage } from \"../error/ClientAuthError\";\nimport { ClientConfigurationError } from \"../error/ClientConfigurationError\";\nimport { ResponseHandler } from \"../response/ResponseHandler\";\nimport { CacheRecord } from \"../cache/entities/CacheRecord\";\nimport { CacheOutcome } from \"../utils/Constants\";\nimport { IPerformanceClient } from \"../telemetry/performance/IPerformanceClient\";\n\nexport class SilentFlowClient extends BaseClient {\n \n constructor(configuration: ClientConfiguration, performanceClient?: IPerformanceClient) {\n super(configuration,performanceClient);\n }\n \n /**\n * Retrieves a token from cache if it is still valid, or uses the cached refresh token to renew\n * the given token and returns the renewed token\n * @param request\n */\n async acquireToken(request: CommonSilentFlowRequest): Promise<AuthenticationResult> {\n try {\n return await this.acquireCachedToken(request);\n } catch (e) {\n if (e instanceof ClientAuthError && e.errorCode === ClientAuthErrorMessage.tokenRefreshRequired.code) {\n const refreshTokenClient = new RefreshTokenClient(this.config, this.performanceClient);\n return refreshTokenClient.acquireTokenByRefreshToken(request);\n } else {\n throw e;\n }\n }\n }\n \n /**\n * Retrieves token from cache or throws an error if it must be refreshed.\n * @param request\n */\n async acquireCachedToken(request: CommonSilentFlowRequest): Promise<AuthenticationResult> {\n // Cannot renew token if no request object is given.\n if (!request) {\n throw ClientConfigurationError.createEmptyTokenRequestError();\n }\n\n if (request.forceRefresh) {\n // Must refresh due to present force_refresh flag.\n this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.FORCE_REFRESH);\n this.logger.info(\"SilentFlowClient:acquireCachedToken - Skipping cache because forceRefresh is true.\");\n throw ClientAuthError.createRefreshRequiredError();\n }\n\n // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases\n if (!request.account) {\n throw ClientAuthError.createNoAccountInSilentRequestError();\n }\n\n const environment = request.authority || this.authority.getPreferredCache();\n\n const cacheRecord = this.cacheManager.readCacheRecord(request.account, this.config.authOptions.clientId, request, environment);\n\n if (!cacheRecord.accessToken) {\n // Must refresh due to non-existent access_token.\n this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN);\n this.logger.info(\"SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.\");\n throw ClientAuthError.createRefreshRequiredError();\n } else if (\n TimeUtils.wasClockTurnedBack(cacheRecord.accessToken.cachedAt) ||\n TimeUtils.isTokenExpired(cacheRecord.accessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)\n ) {\n // Must refresh due to expired access_token.\n this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED);\n this.logger.info(`SilentFlowClient:acquireCachedToken - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`);\n throw ClientAuthError.createRefreshRequiredError();\n } else if (cacheRecord.accessToken.refreshOn && TimeUtils.isTokenExpired(cacheRecord.accessToken.refreshOn, 0)) {\n // Must refresh due to the refresh_in value.\n this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.REFRESH_CACHED_ACCESS_TOKEN);\n this.logger.info(\"SilentFlowClient:acquireCachedToken - Cached access token's refreshOn property has been exceeded'.\");\n throw ClientAuthError.createRefreshRequiredError();\n }\n\n if (this.config.serverTelemetryManager) {\n this.config.serverTelemetryManager.incrementCacheHits();\n }\n\n return await this.generateResultFromCacheRecord(cacheRecord, request);\n }\n\n /**\n * Helper function to build response object from the CacheRecord\n * @param cacheRecord\n */\n private async generateResultFromCacheRecord(cacheRecord: CacheRecord, request: CommonSilentFlowRequest): Promise<AuthenticationResult> {\n let idTokenObj: AuthToken | undefined;\n if (cacheRecord.idToken) {\n idTokenObj = new AuthToken(cacheRecord.idToken.secret, this.config.cryptoInterface);\n }\n\n // token max_age check\n if (request.maxAge || (request.maxAge === 0)) {\n const authTime = idTokenObj?.claims.auth_time;\n if (!authTime) {\n throw ClientAuthError.createAuthTimeNotFoundError();\n }\n\n AuthToken.checkMaxAge(authTime, request.maxAge);\n }\n\n return await ResponseHandler.generateAuthenticationResult(\n this.cryptoUtils,\n this.authority,\n cacheRecord,\n true,\n request,\n idTokenObj\n );\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAAA;;;AAGG;AAgBH,IAAA,gBAAA,kBAAA,UAAA,MAAA,EAAA;IAAsC,SAAU,CAAA,gBAAA,EAAA,MAAA,CAAA,CAAA;IAE5C,SAAY,gBAAA,CAAA,aAAkC,EAAE,iBAAsC,EAAA;eAClF,MAAM,CAAA,IAAA,CAAA,IAAA,EAAA,aAAa,EAAC,iBAAiB,CAAC,IAAA,IAAA,CAAA;KAC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AAU,CAAE,MAAM,CAAC,SAAS,CAAC;4BAC9C,IAAI,CAAC,QAAQ,EAAE;AACX,gCAAA,MAAM,eAAe,CAAC,2BAA2B,EAAE,CAAC;AACvD,6BAAA;4BAED,SAAS,CAAC,WAAW,CAAC,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC;AACnD,yBAAA;wBAEM,OAAM,CAAA,CAAA,YAAA,eAAe,CAAC,4BAA4B,CACrD,IAAI,CAAC,WAAW,EAChB,IAAI,CAAC,SAAS,EACd,WAAW,EACX,IAAI,EACJ,OAAO,EACP,UAAU,CACb,CAAA,CAAA;AAPD,oBAAA,KAAA,CAAA,EAAA,OAAA,CAAA,CAAA,aAAO,SAON,CAAC,CAAA;;;;AACL,KAAA,CAAA;IACL,OAAC,gBAAA,CAAA;AAAD,CA1GA,CAAsC,UAAU,CA0G/C;;;;"}
\ No newline at end of file
{"version":3,"file":"UsernamePasswordClient.d.ts","sourceRoot":"","sources":["../../src/client/UsernamePasswordClient.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAE,6BAA6B,EAAE,MAAM,0CAA0C,CAAC;AACzF,OAAO,EAAE,oBAAoB,EAAE,MAAM,kCAAkC,CAAC;AAYxE;;;GAGG;AACH,qBAAa,sBAAuB,SAAQ,UAAU;gBAEtC,aAAa,EAAE,mBAAmB;IAI9C;;;;OAIG;IACG,YAAY,CAAC,OAAO,EAAE,6BAA6B,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC;IAsBhG;;;;OAIG;YACW,mBAAmB;IAqBjC;;;OAGG;IACH,OAAO,CAAC,sBAAsB;CA6CjC"}
\ No newline at end of file
/*! @azure/msal-common v9.0.1 2022-12-07 */
'use strict';
import { __extends, __awaiter, __generator } from '../_virtual/_tslib.js';
import { BaseClient } from './BaseClient.js';
import { ResponseHandler } from '../response/ResponseHandler.js';
import { RequestParameterBuilder } from '../request/RequestParameterBuilder.js';
import { GrantType } from '../utils/Constants.js';
import { StringUtils } from '../utils/StringUtils.js';
import { TimeUtils } from '../utils/TimeUtils.js';
import { CcsCredentialType } from '../account/CcsCredential.js';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Oauth2.0 Password grant client
* Note: We are only supporting public clients for password grant and for purely testing purposes
*/
var UsernamePasswordClient = /** @class */ (function (_super) {
__extends(UsernamePasswordClient, _super);
function UsernamePasswordClient(configuration) {
return _super.call(this, configuration) || this;
}
/**
* API to acquire a token by passing the username and password to the service in exchage of credentials
* password_grant
* @param request
*/
UsernamePasswordClient.prototype.acquireToken = function (request) {
return __awaiter(this, void 0, void 0, function () {
var reqTimestamp, response, responseHandler, tokenResponse;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.logger.info("in acquireToken call");
reqTimestamp = TimeUtils.nowSeconds();
return [4 /*yield*/, this.executeTokenRequest(this.authority, request)];
case 1:
response = _a.sent();
responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
// Validate response. This function throws a server error if an error is returned by the server.
responseHandler.validateTokenResponse(response.body);
tokenResponse = responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request);
return [2 /*return*/, tokenResponse];
}
});
});
};
/**
* Executes POST request to token endpoint
* @param authority
* @param request
*/
UsernamePasswordClient.prototype.executeTokenRequest = function (authority, request) {
return __awaiter(this, void 0, void 0, function () {
var thumbprint, requestBody, headers;
return __generator(this, function (_a) {
thumbprint = {
clientId: this.config.authOptions.clientId,
authority: authority.canonicalAuthority,
scopes: request.scopes,
claims: request.claims,
authenticationScheme: request.authenticationScheme,
resourceRequestMethod: request.resourceRequestMethod,
resourceRequestUri: request.resourceRequestUri,
shrClaims: request.shrClaims,
sshKid: request.sshKid
};
requestBody = this.createTokenRequestBody(request);
headers = this.createTokenRequestHeaders({
credential: request.username,
type: CcsCredentialType.UPN
});
return [2 /*return*/, this.executePostToTokenEndpoint(authority.tokenEndpoint, requestBody, headers, thumbprint)];
});
});
};
/**
* Generates a map for all the params to be sent to the service
* @param request
*/
UsernamePasswordClient.prototype.createTokenRequestBody = function (request) {
var parameterBuilder = new RequestParameterBuilder();
parameterBuilder.addClientId(this.config.authOptions.clientId);
parameterBuilder.addUsername(request.username);
parameterBuilder.addPassword(request.password);
parameterBuilder.addScopes(request.scopes);
parameterBuilder.addResponseTypeForTokenAndIdToken();
parameterBuilder.addGrantType(GrantType.RESOURCE_OWNER_PASSWORD_GRANT);
parameterBuilder.addClientInfo();
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
var correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();
parameterBuilder.addCorrelationId(correlationId);
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
var clientAssertion = this.config.clientCredentials.clientAssertion;
parameterBuilder.addClientAssertion(clientAssertion.assertion);
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
if (this.config.systemOptions.preventCorsPreflight && request.username) {
parameterBuilder.addCcsUpn(request.username);
}
return parameterBuilder.createQueryString();
};
return UsernamePasswordClient;
}(BaseClient));
export { UsernamePasswordClient };
//# sourceMappingURL=UsernamePasswordClient.js.map
{"version":3,"file":"UsernamePasswordClient.js","sources":["../../src/client/UsernamePasswordClient.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { BaseClient } from \"./BaseClient\";\nimport { ClientConfiguration } from \"../config/ClientConfiguration\";\nimport { CommonUsernamePasswordRequest } from \"../request/CommonUsernamePasswordRequest\";\nimport { AuthenticationResult } from \"../response/AuthenticationResult\";\nimport { ResponseHandler } from \"../response/ResponseHandler\";\nimport { Authority } from \"../authority/Authority\";\nimport { NetworkResponse } from \"../network/NetworkManager\";\nimport { ServerAuthorizationTokenResponse } from \"../response/ServerAuthorizationTokenResponse\";\nimport { RequestParameterBuilder } from \"../request/RequestParameterBuilder\";\nimport { GrantType } from \"../utils/Constants\";\nimport { StringUtils } from \"../utils/StringUtils\";\nimport { RequestThumbprint } from \"../network/RequestThumbprint\";\nimport { TimeUtils } from \"../utils/TimeUtils\";\nimport { CcsCredentialType } from \"../account/CcsCredential\";\n\n/**\n * Oauth2.0 Password grant client\n * Note: We are only supporting public clients for password grant and for purely testing purposes\n */\nexport class UsernamePasswordClient extends BaseClient {\n\n constructor(configuration: ClientConfiguration) {\n super(configuration);\n }\n\n /**\n * API to acquire a token by passing the username and password to the service in exchage of credentials\n * password_grant\n * @param request\n */\n async acquireToken(request: CommonUsernamePasswordRequest): Promise<AuthenticationResult | null> {\n this.logger.info(\"in acquireToken call\");\n\n const reqTimestamp = TimeUtils.nowSeconds();\n const response = await this.executeTokenRequest(this.authority, request);\n\n const responseHandler = new ResponseHandler(\n this.config.authOptions.clientId,\n this.cacheManager,\n this.cryptoUtils,\n this.logger,\n this.config.serializableCache,\n this.config.persistencePlugin\n );\n\n // Validate response. This function throws a server error if an error is returned by the server.\n responseHandler.validateTokenResponse(response.body);\n const tokenResponse = responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request);\n\n return tokenResponse;\n }\n\n /**\n * Executes POST request to token endpoint\n * @param authority\n * @param request\n */\n private async executeTokenRequest(authority: Authority, request: CommonUsernamePasswordRequest): Promise<NetworkResponse<ServerAuthorizationTokenResponse>> {\n const thumbprint: RequestThumbprint = {\n clientId: this.config.authOptions.clientId,\n authority: authority.canonicalAuthority,\n scopes: request.scopes,\n claims: request.claims,\n authenticationScheme: request.authenticationScheme,\n resourceRequestMethod: request.resourceRequestMethod,\n resourceRequestUri: request.resourceRequestUri,\n shrClaims: request.shrClaims,\n sshKid: request.sshKid\n };\n const requestBody = this.createTokenRequestBody(request);\n const headers: Record<string, string> = this.createTokenRequestHeaders({\n credential: request.username,\n type: CcsCredentialType.UPN\n });\n\n return this.executePostToTokenEndpoint(authority.tokenEndpoint, requestBody, headers, thumbprint);\n }\n\n /**\n * Generates a map for all the params to be sent to the service\n * @param request\n */\n private createTokenRequestBody(request: CommonUsernamePasswordRequest): string {\n const parameterBuilder = new RequestParameterBuilder();\n\n parameterBuilder.addClientId(this.config.authOptions.clientId);\n parameterBuilder.addUsername(request.username);\n parameterBuilder.addPassword(request.password);\n\n parameterBuilder.addScopes(request.scopes);\n\n parameterBuilder.addResponseTypeForTokenAndIdToken();\n\n parameterBuilder.addGrantType(GrantType.RESOURCE_OWNER_PASSWORD_GRANT);\n parameterBuilder.addClientInfo();\n\n parameterBuilder.addLibraryInfo(this.config.libraryInfo);\n parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);\n parameterBuilder.addThrottling();\n\n if (this.serverTelemetryManager) {\n parameterBuilder.addServerTelemetry(this.serverTelemetryManager);\n }\n\n const correlationId = request.correlationId || this.config.cryptoInterface.createNewGuid();\n parameterBuilder.addCorrelationId(correlationId);\n\n if (this.config.clientCredentials.clientSecret) {\n parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);\n }\n\n if (this.config.clientCredentials.clientAssertion) {\n const clientAssertion = this.config.clientCredentials.clientAssertion;\n parameterBuilder.addClientAssertion(clientAssertion.assertion);\n parameterBuilder.addClientAssertionType(clientAssertion.assertionType);\n }\n\n if (!StringUtils.isEmptyObj(request.claims) || this.config.authOptions.clientCapabilities && this.config.authOptions.clientCapabilities.length > 0) {\n parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);\n }\n\n if (this.config.systemOptions.preventCorsPreflight && request.username) {\n parameterBuilder.addCcsUpn(request.username);\n }\n\n return parameterBuilder.createQueryString();\n }\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAAA;;;AAGG;AAiBH;;;AAGG;AACH,IAAA,sBAAA,kBAAA,UAAA,MAAA,EAAA;IAA4C,SAAU,CAAA,sBAAA,EAAA,MAAA,CAAA,CAAA;AAElD,IAAA,SAAA,sBAAA,CAAY,aAAkC,EAAA;AAC1C,QAAA,OAAA,MAAA,CAAA,IAAA,CAAA,IAAA,EAAM,aAAa,CAAC,IAAA,IAAA,CAAA;KACvB;AAED;;;;AAIG;IACG,sBAAY,CAAA,SAAA,CAAA,YAAA,GAAlB,UAAmB,OAAsC,EAAA;;;;;;AACrD,wBAAA,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;AAEnC,wBAAA,YAAY,GAAG,SAAS,CAAC,UAAU,EAAE,CAAC;wBAC3B,OAAM,CAAA,CAAA,YAAA,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAA,CAAA;;AAAlE,wBAAA,QAAQ,GAAG,EAAuD,CAAA,IAAA,EAAA,CAAA;AAElE,wBAAA,eAAe,GAAG,IAAI,eAAe,CACvC,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,QAAQ,EAChC,IAAI,CAAC,YAAY,EACjB,IAAI,CAAC,WAAW,EAChB,IAAI,CAAC,MAAM,EACX,IAAI,CAAC,MAAM,CAAC,iBAAiB,EAC7B,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAChC,CAAC;;AAGF,wBAAA,eAAe,CAAC,qBAAqB,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;AAC/C,wBAAA,aAAa,GAAG,eAAe,CAAC,yBAAyB,CAAC,QAAQ,CAAC,IAAI,EAAE,IAAI,CAAC,SAAS,EAAE,YAAY,EAAE,OAAO,CAAC,CAAC;AAEtH,wBAAA,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AA,gBAAgB,CAAC,sBAAsB,CAAC,eAAe,CAAC,aAAa,CAAC,CAAC;AAC1E,SAAA;AAED,QAAA,IAAI,CAAC,WAAW,CAAC,UAAU,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,kBAAkB,IAAI,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,kBAAkB,CAAC,MAAM,GAAG,CAAC,EAAE;AAChJ,YAAA,gBAAgB,CAAC,SAAS,CAAC,OAAO,CAAC,MAAM,EAAE,IAAI,CAAC,MAAM,CAAC,WAAW,CAAC,kBAAkB,CAAC,CAAC;AAC1F,SAAA;QAED,IAAI,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,oBAAoB,IAAI,OAAO,CAAC,QAAQ,EAAE;AACpE,YAAA,gBAAgB,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;AAChD,SAAA;AAED,QAAA,OAAO,gBAAgB,CAAC,iBAAiB,EAAE,CAAC;KAC/C,CAAA;IACL,OAAC,sBAAA,CAAA;AAAD,CA5GA,CAA4C,UAAU,CA4GrD;;;;"}
\ No newline at end of file
/**
* Extensibility interface, which allows the app developer to return a token, based on the passed-in parameters, instead of fetching tokens from
* the Identity Provider (AAD).
* Developers need to construct and return an AppTokenProviderResult object back to MSAL. MSAL will cache the token response
* in the same way it would do if the result were comming from AAD.
* This extensibility point is only defined for the client_credential flow, i.e. acquireTokenByClientCredential and
* meant for Azure SDK to enhance Managed Identity support.
*/
export interface IAppTokenProvider {
(appTokenProviderParameters: AppTokenProviderParameters): Promise<AppTokenProviderResult>;
}
/**
* Input object for the IAppTokenProvider extensiblity. MSAL will create this object, which can be used
* to help create an AppTokenProviderResult.
*
* - correlationId - the correlation Id associated with the request
* - tenantId - the tenant Id for which the token must be provided
* - scopes - the scopes for which the token must be provided
* - claims - any extra claims that the token must satisfy
*/
export declare type AppTokenProviderParameters = {
readonly correlationId?: string;
readonly tenantId: string;
readonly scopes: Array<string>;
readonly claims?: string;
};
/**
* Output object for IAppTokenProvider extensiblity.
*
* - accessToken - the actual access token, typically in JWT format, that satisfies the request data AppTokenProviderParameters
* - expiresInSeconds - how long the tokens has before expiry, in seconds. Similar to the "expires_in" field in an AAD token response.
* - refreshInSeconds - how long the token has before it should be proactively refreshed. Similar to the "refresh_in" field in an AAD token response.
*/
export declare type AppTokenProviderResult = {
accessToken: string;
expiresInSeconds: number;
refreshInSeconds?: number;
};
//# sourceMappingURL=AppTokenProvider.d.ts.map
\ No newline at end of file
{"version":3,"file":"AppTokenProvider.d.ts","sourceRoot":"","sources":["../../src/config/AppTokenProvider.ts"],"names":[],"mappings":"AAKA;;;;;;;GAOG;AACH,MAAM,WAAW,iBAAiB;IAC9B,CAAC,0BAA0B,EAAE,0BAA0B,GAAG,OAAO,CAAC,sBAAsB,CAAC,CAAC;CAC7F;AAED;;;;;;;;GAQG;AACH,oBAAY,0BAA0B,GAAG;IACrC,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC;IAC/B,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAC5B,CAAC;AAEF;;;;;;GAMG;AACH,oBAAY,sBAAsB,GAAG;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,gBAAgB,EAAE,MAAM,CAAC;IACzB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC7B,CAAC"}
\ No newline at end of file
import { INetworkModule } from "../network/INetworkModule";
import { ICrypto } from "../crypto/ICrypto";
import { ILoggerCallback, LogLevel } from "../logger/Logger";
import { Authority } from "../authority/Authority";
import { AzureCloudInstance } from "../authority/AuthorityOptions";
import { CacheManager } from "../cache/CacheManager";
import { ServerTelemetryManager } from "../telemetry/server/ServerTelemetryManager";
import { ICachePlugin } from "../cache/interface/ICachePlugin";
import { ISerializableTokenCache } from "../cache/interface/ISerializableTokenCache";
import { ClientCredentials } from "../account/ClientCredentials";
/**
* Use the configuration object to configure MSAL Modules and initialize the base interfaces for MSAL.
*
* This object allows you to configure important elements of MSAL functionality:
* - authOptions - Authentication for application
* - cryptoInterface - Implementation of crypto functions
* - libraryInfo - Library metadata
* - telemetry - Telemetry options and data
* - loggerOptions - Logging for application
* - networkInterface - Network implementation
* - storageInterface - Storage implementation
* - systemOptions - Additional library options
* - clientCredentials - Credentials options for confidential clients
*/
export declare type ClientConfiguration = {
authOptions: AuthOptions;
systemOptions?: SystemOptions;
loggerOptions?: LoggerOptions;
storageInterface?: CacheManager;
networkInterface?: INetworkModule;
cryptoInterface?: ICrypto;
clientCredentials?: ClientCredentials;
libraryInfo?: LibraryInfo;
telemetry?: TelemetryOptions;
serverTelemetryManager?: ServerTelemetryManager | null;
persistencePlugin?: ICachePlugin | null;
serializableCache?: ISerializableTokenCache | null;
};
export declare type CommonClientConfiguration = {
authOptions: Required<AuthOptions>;
systemOptions: Required<SystemOptions>;
loggerOptions: Required<LoggerOptions>;
storageInterface: CacheManager;
networkInterface: INetworkModule;
cryptoInterface: Required<ICrypto>;
libraryInfo: LibraryInfo;
telemetry: Required<TelemetryOptions>;
serverTelemetryManager: ServerTelemetryManager | null;
clientCredentials: ClientCredentials;
persistencePlugin: ICachePlugin | null;
serializableCache: ISerializableTokenCache | null;
};
/**
* Use this to configure the auth options in the ClientConfiguration object
*
* - clientId - Client ID of your app registered with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview in Microsoft Identity Platform
* - authority - You can configure a specific authority, defaults to " " or "https://login.microsoftonline.com/common"
* - knownAuthorities - An array of URIs that are known to be valid. Used in B2C scenarios.
* - cloudDiscoveryMetadata - A string containing the cloud discovery response. Used in AAD scenarios.
* - clientCapabilities - Array of capabilities which will be added to the claims.access_token.xms_cc request property on every network request.
* - protocolMode - Enum that represents the protocol that msal follows. Used for configuring proper endpoints.
* - skipAuthorityMetadataCache - A flag to choose whether to use or not use the local metadata cache during authority initialization. Defaults to false.
*/
export declare type AuthOptions = {
clientId: string;
authority: Authority;
clientCapabilities?: Array<string>;
azureCloudOptions?: AzureCloudOptions;
skipAuthorityMetadataCache?: boolean;
};
/**
* Use this to configure token renewal info in the Configuration object
*
* - tokenRenewalOffsetSeconds - Sets the window of offset needed to renew the token before expiry
*/
export declare type SystemOptions = {
tokenRenewalOffsetSeconds?: number;
preventCorsPreflight?: boolean;
proxyUrl?: string;
};
/**
* Use this to configure the logging that MSAL does, by configuring logger options in the Configuration object
*
* - loggerCallback - Callback for logger
* - piiLoggingEnabled - Sets whether pii logging is enabled
* - logLevel - Sets the level at which logging happens
* - correlationId - Sets the correlationId printed by the logger
*/
export declare type LoggerOptions = {
loggerCallback?: ILoggerCallback;
piiLoggingEnabled?: boolean;
logLevel?: LogLevel;
correlationId?: string;
};
/**
* Library-specific options
*/
export declare type LibraryInfo = {
sku: string;
version: string;
cpu: string;
os: string;
};
/**
* AzureCloudInstance specific options
*
* - azureCloudInstance - string enum providing short notation for soverign and public cloud authorities
* - tenant - provision to provide the tenant info
*/
export declare type AzureCloudOptions = {
azureCloudInstance: AzureCloudInstance;
tenant?: string;
};
export declare type TelemetryOptions = {
application: ApplicationTelemetry;
};
/**
* Telemetry information sent on request
* - appName: Unique string name of an application
* - appVersion: Version of the application using MSAL
*/
export declare type ApplicationTelemetry = {
appName: string;
appVersion: string;
};
export declare const DEFAULT_SYSTEM_OPTIONS: Required<SystemOptions>;
/**
* Function that sets the default options when not explicitly configured from app developer
*
* @param Configuration
*
* @returns Configuration
*/
export declare function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions: userSystemOptions, loggerOptions: userLoggerOption, storageInterface: storageImplementation, networkInterface: networkImplementation, cryptoInterface: cryptoImplementation, clientCredentials: clientCredentials, libraryInfo: libraryInfo, telemetry: telemetry, serverTelemetryManager: serverTelemetryManager, persistencePlugin: persistencePlugin, serializableCache: serializableCache, }: ClientConfiguration): CommonClientConfiguration;
//# sourceMappingURL=ClientConfiguration.d.ts.map
\ No newline at end of file
{"version":3,"file":"ClientConfiguration.d.ts","sourceRoot":"","sources":["../../src/config/ClientConfiguration.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAC3D,OAAO,EAAiC,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAE3E,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAG7D,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,OAAO,EAAE,YAAY,EAAuB,MAAM,uBAAuB,CAAC;AAC1E,OAAO,EAAE,sBAAsB,EAAE,MAAM,4CAA4C,CAAC;AACpF,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAC/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,4CAA4C,CAAC;AACrF,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAKjE;;;;;;;;;;;;;GAaG;AACH,oBAAY,mBAAmB,GAAG;IAC9B,WAAW,EAAE,WAAW,CAAC;IACzB,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,gBAAgB,CAAC,EAAE,YAAY,CAAC;IAChC,gBAAgB,CAAC,EAAE,cAAc,CAAC;IAClC,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,WAAW,CAAC,EAAE,WAAW,CAAA;IACzB,SAAS,CAAC,EAAE,gBAAgB,CAAC;IAC7B,sBAAsB,CAAC,EAAE,sBAAsB,GAAG,IAAI,CAAC;IACvD,iBAAiB,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;IACxC,iBAAiB,CAAC,EAAE,uBAAuB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;AACH,oBAAY,WAAW,GAAG;IACtB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,EAAE,EAAE,MAAM,CAAA;CACb,CAAC;AAEF;;;;;GAKG;AACH,oBAAY,iBAAiB,GAAG;IAC5B,kBAAkB,EAAE,kBAAkB,CAAC;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,oBAAY,gBAAgB,GAAG;IAC3B,WAAW,EAAE,oBAAoB,CAAC;CACrC,CAAC;AAEF;;;;GAIG;AACH,oBAAY,oBAAoB,GAAG;IAC/B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;CACtB,CAAC;AAEF,eAAO,MAAM,sBAAsB,EAAE,QAAQ,CAAC,aAAa,CAI1D,CAAC;AA8CF;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CACpC,EACI,WAAW,EAAE,eAAe,EAC5B,aAAa,EAAE,iBAAiB,EAChC,aAAa,EAAE,gBAAgB,EAC/B,gBAAgB,EAAE,qBAAqB,EACvC,gBAAgB,EAAE,qBAAqB,EACvC,eAAe,EAAE,oBAAoB,EACrC,iBAAiB,EAAE,iBAAiB,EACpC,WAAW,EAAE,WAAW,EACxB,SAAS,EAAE,SAAS,EACpB,sBAAsB,EAAE,sBAAsB,EAC9C,iBAAiB,EAAE,iBAAiB,EACpC,iBAAiB,EAAE,iBAAiB,GACvC,EAAE,mBAAmB,GAAG,yBAAyB,CAkBrD"}
\ No newline at end of file
/*! @azure/msal-common v9.0.1 2022-12-07 */
'use strict';
import { __assign, __awaiter, __generator } from '../_virtual/_tslib.js';
import { DEFAULT_CRYPTO_IMPLEMENTATION } from '../crypto/ICrypto.js';
import { AuthError } from '../error/AuthError.js';
import { LogLevel } from '../logger/Logger.js';
import { Constants } from '../utils/Constants.js';
import { version } from '../packageMetadata.js';
import { AzureCloudInstance } from '../authority/AuthorityOptions.js';
import { DefaultStorageClass } from '../cache/CacheManager.js';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
// Token renewal offset default in seconds
var DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300;
var DEFAULT_SYSTEM_OPTIONS = {
tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,
preventCorsPreflight: false,
proxyUrl: Constants.EMPTY_STRING
};
var DEFAULT_LOGGER_IMPLEMENTATION = {
loggerCallback: function () {
// allow users to not set loggerCallback
},
piiLoggingEnabled: false,
logLevel: LogLevel.Info,
correlationId: Constants.EMPTY_STRING
};
var DEFAULT_NETWORK_IMPLEMENTATION = {
sendGetRequestAsync: function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Network interface - sendGetRequestAsync() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
});
});
},
sendPostRequestAsync: function () {
return __awaiter(this, void 0, void 0, function () {
var notImplErr;
return __generator(this, function (_a) {
notImplErr = "Network interface - sendPostRequestAsync() has not been implemented";
throw AuthError.createUnexpectedError(notImplErr);
});
});
}
};
var DEFAULT_LIBRARY_INFO = {
sku: Constants.SKU,
version: version,
cpu: Constants.EMPTY_STRING,
os: Constants.EMPTY_STRING
};
var DEFAULT_CLIENT_CREDENTIALS = {
clientSecret: Constants.EMPTY_STRING,
clientAssertion: undefined
};
var DEFAULT_AZURE_CLOUD_OPTIONS = {
azureCloudInstance: AzureCloudInstance.None,
tenant: "" + Constants.DEFAULT_COMMON_TENANT
};
var DEFAULT_TELEMETRY_OPTIONS = {
application: {
appName: "",
appVersion: ""
}
};
/**
* Function that sets the default options when not explicitly configured from app developer
*
* @param Configuration
*
* @returns Configuration
*/
function buildClientConfiguration(_a) {
var userAuthOptions = _a.authOptions, userSystemOptions = _a.systemOptions, userLoggerOption = _a.loggerOptions, storageImplementation = _a.storageInterface, networkImplementation = _a.networkInterface, cryptoImplementation = _a.cryptoInterface, clientCredentials = _a.clientCredentials, libraryInfo = _a.libraryInfo, telemetry = _a.telemetry, serverTelemetryManager = _a.serverTelemetryManager, persistencePlugin = _a.persistencePlugin, serializableCache = _a.serializableCache;
var loggerOptions = __assign(__assign({}, DEFAULT_LOGGER_IMPLEMENTATION), userLoggerOption);
return {
authOptions: buildAuthOptions(userAuthOptions),
systemOptions: __assign(__assign({}, DEFAULT_SYSTEM_OPTIONS), userSystemOptions),
loggerOptions: loggerOptions,
storageInterface: storageImplementation || new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION),
networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,
cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION,
clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS,
libraryInfo: __assign(__assign({}, DEFAULT_LIBRARY_INFO), libraryInfo),
telemetry: __assign(__assign({}, DEFAULT_TELEMETRY_OPTIONS), telemetry),
serverTelemetryManager: serverTelemetryManager || null,
persistencePlugin: persistencePlugin || null,
serializableCache: serializableCache || null,
};
}
/**
* Construct authoptions from the client and platform passed values
* @param authOptions
*/
function buildAuthOptions(authOptions) {
return __assign({ clientCapabilities: [], azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS, skipAuthorityMetadataCache: false }, authOptions);
}
export { DEFAULT_SYSTEM_OPTIONS, buildClientConfiguration };
//# sourceMappingURL=ClientConfiguration.js.map
{"version":3,"file":"ClientConfiguration.js","sources":["../../src/config/ClientConfiguration.ts"],"sourcesContent":["/*\n * Copyright (c) Microsoft Corporation. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport { INetworkModule } from \"../network/INetworkModule\";\nimport { DEFAULT_CRYPTO_IMPLEMENTATION, ICrypto } from \"../crypto/ICrypto\";\nimport { AuthError } from \"../error/AuthError\";\nimport { ILoggerCallback, LogLevel } from \"../logger/Logger\";\nimport { Constants } from \"../utils/Constants\";\nimport { version } from \"../packageMetadata\";\nimport { Authority } from \"../authority/Authority\";\nimport { AzureCloudInstance } from \"../authority/AuthorityOptions\";\nimport { CacheManager, DefaultStorageClass } from \"../cache/CacheManager\";\nimport { ServerTelemetryManager } from \"../telemetry/server/ServerTelemetryManager\";\nimport { ICachePlugin } from \"../cache/interface/ICachePlugin\";\nimport { ISerializableTokenCache } from \"../cache/interface/ISerializableTokenCache\";\nimport { ClientCredentials } from \"../account/ClientCredentials\";\n\n// Token renewal offset default in seconds\nconst DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300;\n\n/**\n * Use the configuration object to configure MSAL Modules and initialize the base interfaces for MSAL.\n *\n * This object allows you to configure important elements of MSAL functionality:\n * - authOptions - Authentication for application\n * - cryptoInterface - Implementation of crypto functions\n * - libraryInfo - Library metadata\n * - telemetry - Telemetry options and data\n * - loggerOptions - Logging for application\n * - networkInterface - Network implementation\n * - storageInterface - Storage implementation\n * - systemOptions - Additional library options\n * - clientCredentials - Credentials options for confidential clients\n */\nexport type ClientConfiguration = {\n authOptions: AuthOptions,\n systemOptions?: SystemOptions,\n loggerOptions?: LoggerOptions,\n storageInterface?: CacheManager,\n networkInterface?: INetworkModule,\n cryptoInterface?: ICrypto,\n clientCredentials?: ClientCredentials,\n libraryInfo?: LibraryInfo\n telemetry?: TelemetryOptions,\n serverTelemetryManager?: ServerTelemetryManager | null,\n persistencePlugin?: ICachePlugin | null,\n serializableCache?: ISerializableTokenCache | null, \n};\n\nexport type CommonClientConfiguration = {\n authOptions: Required<AuthOptions>,\n systemOptions: Required<SystemOptions>,\n loggerOptions : Required<LoggerOptions>,\n storageInterface: CacheManager,\n networkInterface : INetworkModule,\n cryptoInterface : Required<ICrypto>,\n libraryInfo : LibraryInfo,\n telemetry: Required<TelemetryOptions>,\n serverTelemetryManager: ServerTelemetryManager | null,\n clientCredentials: ClientCredentials,\n persistencePlugin: ICachePlugin | null,\n serializableCache: ISerializableTokenCache | null, \n};\n\n/**\n * Use this to configure the auth options in the ClientConfiguration object\n *\n * - clientId - Client ID of your app registered with our Application registration portal : https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredAppsPreview in Microsoft Identity Platform\n * - authority - You can configure a specific authority, defaults to \" \" or \"https://login.microsoftonline.com/common\"\n * - knownAuthorities - An array of URIs that are known to be valid. Used in B2C scenarios.\n * - cloudDiscoveryMetadata - A string containing the cloud discovery response. Used in AAD scenarios.\n * - clientCapabilities - Array of capabilities which will be added to the claims.access_token.xms_cc request property on every network request.\n * - protocolMode - Enum that represents the protocol that msal follows. Used for configuring proper endpoints.\n * - skipAuthorityMetadataCache - A flag to choose whether to use or not use the local metadata cache during authority initialization. Defaults to false.\n */\nexport type AuthOptions = {\n clientId: string;\n authority: Authority;\n clientCapabilities?: Array<string>;\n azureCloudOptions?: AzureCloudOptions;\n skipAuthorityMetadataCache?: boolean;\n};\n\n/**\n * Use this to configure token renewal info in the Configuration object\n *\n * - tokenRenewalOffsetSeconds - Sets the window of offset needed to renew the token before expiry\n */\nexport type SystemOptions = {\n tokenRenewalOffsetSeconds?: number;\n preventCorsPreflight?: boolean;\n proxyUrl?: string;\n};\n\n/**\n * Use this to configure the logging that MSAL does, by configuring logger options in the Configuration object\n *\n * - loggerCallback - Callback for logger\n * - piiLoggingEnabled - Sets whether pii logging is enabled\n * - logLevel - Sets the level at which logging happens\n * - correlationId - Sets the correlationId printed by the logger\n */\nexport type LoggerOptions = {\n loggerCallback?: ILoggerCallback,\n piiLoggingEnabled?: boolean,\n logLevel?: LogLevel,\n correlationId?: string\n};\n\n/**\n * Library-specific options\n */\nexport type LibraryInfo = {\n sku: string,\n version: string,\n cpu: string,\n os: string\n};\n\n/**\n * AzureCloudInstance specific options\n *\n * - azureCloudInstance - string enum providing short notation for soverign and public cloud authorities\n * - tenant - provision to provide the tenant info\n */\nexport type AzureCloudOptions = {\n azureCloudInstance: AzureCloudInstance;\n tenant?: string,\n};\n\nexport type TelemetryOptions = {\n application: ApplicationTelemetry;\n};\n\n/**\n * Telemetry information sent on request\n * - appName: Unique string name of an application\n * - appVersion: Version of the application using MSAL\n */\nexport type ApplicationTelemetry = {\n appName: string;\n appVersion: string;\n};\n\nexport const DEFAULT_SYSTEM_OPTIONS: Required<SystemOptions> = {\n tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC,\n preventCorsPreflight: false,\n proxyUrl: Constants.EMPTY_STRING\n};\n\nconst DEFAULT_LOGGER_IMPLEMENTATION: Required<LoggerOptions> = {\n loggerCallback: () => {\n // allow users to not set loggerCallback\n },\n piiLoggingEnabled: false,\n logLevel: LogLevel.Info,\n correlationId: Constants.EMPTY_STRING\n};\n\nconst DEFAULT_NETWORK_IMPLEMENTATION: INetworkModule = {\n async sendGetRequestAsync<T>(): Promise<T> {\n const notImplErr = \"Network interface - sendGetRequestAsync() has not been implemented\";\n throw AuthError.createUnexpectedError(notImplErr);\n },\n async sendPostRequestAsync<T>(): Promise<T> {\n const notImplErr = \"Network interface - sendPostRequestAsync() has not been implemented\";\n throw AuthError.createUnexpectedError(notImplErr);\n }\n};\n\nconst DEFAULT_LIBRARY_INFO: LibraryInfo = {\n sku: Constants.SKU,\n version: version,\n cpu: Constants.EMPTY_STRING,\n os: Constants.EMPTY_STRING\n};\n\nconst DEFAULT_CLIENT_CREDENTIALS: ClientCredentials = {\n clientSecret: Constants.EMPTY_STRING,\n clientAssertion: undefined\n};\n\nconst DEFAULT_AZURE_CLOUD_OPTIONS: AzureCloudOptions = {\n azureCloudInstance: AzureCloudInstance.None,\n tenant: `${Constants.DEFAULT_COMMON_TENANT}`\n};\n\nconst DEFAULT_TELEMETRY_OPTIONS: Required<TelemetryOptions> = {\n application: {\n appName: \"\",\n appVersion: \"\"\n }\n};\n\n/**\n * Function that sets the default options when not explicitly configured from app developer\n *\n * @param Configuration\n *\n * @returns Configuration\n */\nexport function buildClientConfiguration(\n {\n authOptions: userAuthOptions,\n systemOptions: userSystemOptions,\n loggerOptions: userLoggerOption,\n storageInterface: storageImplementation,\n networkInterface: networkImplementation,\n cryptoInterface: cryptoImplementation,\n clientCredentials: clientCredentials,\n libraryInfo: libraryInfo,\n telemetry: telemetry,\n serverTelemetryManager: serverTelemetryManager,\n persistencePlugin: persistencePlugin,\n serializableCache: serializableCache, \n }: ClientConfiguration): CommonClientConfiguration {\n\n const loggerOptions = { ...DEFAULT_LOGGER_IMPLEMENTATION, ...userLoggerOption };\n\n return {\n authOptions: buildAuthOptions(userAuthOptions),\n systemOptions: { ...DEFAULT_SYSTEM_OPTIONS, ...userSystemOptions },\n loggerOptions: loggerOptions,\n storageInterface: storageImplementation || new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION),\n networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION,\n cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION,\n clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS,\n libraryInfo: { ...DEFAULT_LIBRARY_INFO, ...libraryInfo },\n telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry },\n serverTelemetryManager: serverTelemetryManager || null,\n persistencePlugin: persistencePlugin || null,\n serializableCache: serializableCache || null, \n };\n}\n\n/**\n * Construct authoptions from the client and platform passed values\n * @param authOptions\n */\nfunction buildAuthOptions(authOptions: AuthOptions): Required<AuthOptions> {\n return {\n clientCapabilities: [],\n azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS,\n skipAuthorityMetadataCache: false,\n ...authOptions\n };\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAAA;;;AAGG;AAgBH;AACA,IAAM,gCAAgC,GAAG,GAAG,CAAC;AA8HhC,IAAA,sBAAsB,GAA4B;AAC3D,IAAA,yBAAyB,EAAE,gCAAgC;AAC3D,IAAA,oBAAoB,EAAE,KAAK;IAC3B,QAAQ,EAAE,SAAS,CAAC,YAAY;EAClC;AAEF,IAAM,6BAA6B,GAA4B;AAC3D,IAAA,cAAc,EAAE,YAAA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,QAAA,CAAA,EACI,kBAAkB,EAAE,EAAE,EACtB,iBAAiB,EAAE,2BAA2B,EAC9C,0BAA0B,EAAE,KAAK,EAAA,EAC9B,WAAW,CAChB,CAAA;AACN;;;;"}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment