Commit iniziale

This commit is contained in:
Paolo A
2025-02-18 22:59:07 +00:00
commit 4bbf35cefb
6879 changed files with 623784 additions and 0 deletions

View File

@@ -0,0 +1,76 @@
import { BaseClient } from "./BaseClient.js";
import { CommonAuthorizationUrlRequest } from "../request/CommonAuthorizationUrlRequest.js";
import { CommonAuthorizationCodeRequest } from "../request/CommonAuthorizationCodeRequest.js";
import { ClientConfiguration } from "../config/ClientConfiguration.js";
import { AuthenticationResult } from "../response/AuthenticationResult.js";
import { ServerAuthorizationCodeResponse } from "../response/ServerAuthorizationCodeResponse.js";
import { CommonEndSessionRequest } from "../request/CommonEndSessionRequest.js";
import { AuthorizationCodePayload } from "../response/AuthorizationCodePayload.js";
import { IPerformanceClient } from "../telemetry/performance/IPerformanceClient.js";
/**
* Oauth2.0 Authorization Code client
* @internal
*/
export declare class AuthorizationCodeClient extends BaseClient {
protected includeRedirectUri: boolean;
private oidcDefaultScopes;
constructor(configuration: ClientConfiguration, performanceClient?: IPerformanceClient);
/**
* Creates the URL of the authorization request letting the user input credentials and consent to the
* application. The URL target the /authorize endpoint of the authority configured in the
* application object.
*
* Once the user inputs their credentials and consents, the authority will send a response to the redirect URI
* sent in the request and should contain an authorization code, which can then be used to acquire tokens via
* acquireToken(AuthorizationCodeRequest)
* @param request
*/
getAuthCodeUrl(request: CommonAuthorizationUrlRequest): Promise<string>;
/**
* API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the
* authorization_code_grant
* @param request
*/
acquireToken(request: CommonAuthorizationCodeRequest, authCodePayload?: AuthorizationCodePayload): Promise<AuthenticationResult>;
/**
* Handles the hash fragment response from public client code request. Returns a code response used by
* the client to exchange for a token in acquireToken.
* @param hashFragment
*/
handleFragmentResponse(serverParams: ServerAuthorizationCodeResponse, cachedState: string): AuthorizationCodePayload;
/**
* Used to log out the current user, and redirect the user to the postLogoutRedirectUri.
* Default behaviour is to redirect the user to `window.location.href`.
* @param authorityUri
*/
getLogoutUri(logoutRequest: CommonEndSessionRequest): string;
/**
* Executes POST request to token endpoint
* @param authority
* @param request
*/
private executeTokenRequest;
/**
* Generates a map for all the params to be sent to the service
* @param request
*/
private createTokenRequestBody;
/**
* This API validates the `AuthorizationCodeUrlRequest` and creates a URL
* @param request
*/
private createAuthCodeUrlQueryString;
/**
* This API validates the `EndSessionRequest` and creates a URL
* @param request
*/
private createLogoutUrlQueryString;
private addExtraQueryParams;
/**
* Helper to get sid from account. Returns null if idTokenClaims are not present or sid is not present.
* @param account
*/
private extractAccountSid;
private extractLoginHint;
}
//# sourceMappingURL=AuthorizationCodeClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"AuthorizationCodeClient.d.ts","sourceRoot":"","sources":["../../src/client/AuthorizationCodeClient.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,6BAA6B,EAAE,MAAM,6CAA6C,CAAC;AAC5F,OAAO,EAAE,8BAA8B,EAAE,MAAM,8CAA8C,CAAC;AAW9F,OAAO,EACH,mBAAmB,EAEtB,MAAM,kCAAkC,CAAC;AAI1C,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAO3E,OAAO,EAAE,+BAA+B,EAAE,MAAM,gDAAgD,CAAC;AACjG,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAGhF,OAAO,EAAE,wBAAwB,EAAE,MAAM,yCAAyC,CAAC;AAanF,OAAO,EAAE,kBAAkB,EAAE,MAAM,gDAAgD,CAAC;AAMpF;;;GAGG;AACH,qBAAa,uBAAwB,SAAQ,UAAU;IAEnD,SAAS,CAAC,kBAAkB,EAAE,OAAO,CAAQ;IAC7C,OAAO,CAAC,iBAAiB,CAAC;gBAGtB,aAAa,EAAE,mBAAmB,EAClC,iBAAiB,CAAC,EAAE,kBAAkB;IAO1C;;;;;;;;;OASG;IACG,cAAc,CAChB,OAAO,EAAE,6BAA6B,GACvC,OAAO,CAAC,MAAM,CAAC;IAoBlB;;;;OAIG;IACG,YAAY,CACd,OAAO,EAAE,8BAA8B,EACvC,eAAe,CAAC,EAAE,wBAAwB,GAC3C,OAAO,CAAC,oBAAoB,CAAC;IAwDhC;;;;OAIG;IACH,sBAAsB,CAClB,YAAY,EAAE,+BAA+B,EAC7C,WAAW,EAAE,MAAM,GACpB,wBAAwB;IA2B3B;;;;OAIG;IACH,YAAY,CAAC,aAAa,EAAE,uBAAuB,GAAG,MAAM;IAgB5D;;;;OAIG;YACW,mBAAmB;IA0EjC;;;OAGG;YACW,sBAAsB;IAoMpC;;;OAGG;YACW,4BAA4B;IA4P1C;;;OAGG;IACH,OAAO,CAAC,0BAA0B;IAmClC,OAAO,CAAC,mBAAmB;IAqB3B;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAIzB,OAAO,CAAC,gBAAgB;CAG3B"}

View File

@@ -0,0 +1,473 @@
/*! @azure/msal-common v15.1.1 2025-02-05 */
'use strict';
import { BaseClient } from './BaseClient.mjs';
import { RequestParameterBuilder } from '../request/RequestParameterBuilder.mjs';
import { Separators, GrantType, AuthenticationScheme, PromptValue, HeaderNames } from '../utils/Constants.mjs';
import { CLIENT_ID, RETURN_SPA_CODE } from '../constants/AADServerParamKeys.mjs';
import { isOidcProtocolMode } from '../config/ClientConfiguration.mjs';
import { ResponseHandler } from '../response/ResponseHandler.mjs';
import { StringUtils } from '../utils/StringUtils.mjs';
import { createClientAuthError } from '../error/ClientAuthError.mjs';
import { UrlString } from '../url/UrlString.mjs';
import { PopTokenGenerator } from '../crypto/PopTokenGenerator.mjs';
import { nowSeconds } from '../utils/TimeUtils.mjs';
import { buildClientInfo, buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs';
import { CcsCredentialType } from '../account/CcsCredential.mjs';
import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs';
import { RequestValidator } from '../request/RequestValidator.mjs';
import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs';
import { invokeAsync } from '../utils/FunctionWrappers.mjs';
import { getClientAssertion } from '../utils/ClientAssertionUtils.mjs';
import { requestCannotBeMade, authorizationCodeMissingFromServerResponse } from '../error/ClientAuthErrorCodes.mjs';
import { logoutRequestEmpty, missingSshJwk } from '../error/ClientConfigurationErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Oauth2.0 Authorization Code client
* @internal
*/
class AuthorizationCodeClient extends BaseClient {
constructor(configuration, performanceClient) {
super(configuration, performanceClient);
// Flag to indicate if client is for hybrid spa auth code redemption
this.includeRedirectUri = true;
this.oidcDefaultScopes =
this.config.authOptions.authority.options.OIDCOptions?.defaultScopes;
}
/**
* Creates the URL of the authorization request letting the user input credentials and consent to the
* application. The URL target the /authorize endpoint of the authority configured in the
* application object.
*
* Once the user inputs their credentials and consents, the authority will send a response to the redirect URI
* sent in the request and should contain an authorization code, which can then be used to acquire tokens via
* acquireToken(AuthorizationCodeRequest)
* @param request
*/
async getAuthCodeUrl(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.GetAuthCodeUrl, request.correlationId);
const queryString = await invokeAsync(this.createAuthCodeUrlQueryString.bind(this), PerformanceEvents.AuthClientCreateQueryString, this.logger, this.performanceClient, request.correlationId)(request);
return UrlString.appendQueryString(this.authority.authorizationEndpoint, queryString);
}
/**
* API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the
* authorization_code_grant
* @param request
*/
async acquireToken(request, authCodePayload) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientAcquireToken, request.correlationId);
if (!request.code) {
throw createClientAuthError(requestCannotBeMade);
}
const reqTimestamp = nowSeconds();
const response = await invokeAsync(this.executeTokenRequest.bind(this), PerformanceEvents.AuthClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(this.authority, request);
// Retrieve requestId from response headers
const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin, this.performanceClient);
// Validate response. This function throws a server error if an error is returned by the server.
responseHandler.validateTokenResponse(response.body);
return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), PerformanceEvents.HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, authCodePayload, undefined, undefined, undefined, requestId);
}
/**
* Handles the hash fragment response from public client code request. Returns a code response used by
* the client to exchange for a token in acquireToken.
* @param hashFragment
*/
handleFragmentResponse(serverParams, cachedState) {
// Handle responses.
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, null, null);
// Get code response
responseHandler.validateServerAuthorizationCodeResponse(serverParams, cachedState);
// throw when there is no auth code in the response
if (!serverParams.code) {
throw createClientAuthError(authorizationCodeMissingFromServerResponse);
}
return serverParams;
}
/**
* Used to log out the current user, and redirect the user to the postLogoutRedirectUri.
* Default behaviour is to redirect the user to `window.location.href`.
* @param authorityUri
*/
getLogoutUri(logoutRequest) {
// Throw error if logoutRequest is null/undefined
if (!logoutRequest) {
throw createClientConfigurationError(logoutRequestEmpty);
}
const queryString = this.createLogoutUrlQueryString(logoutRequest);
// Construct logout URI
return UrlString.appendQueryString(this.authority.endSessionEndpoint, queryString);
}
/**
* Executes POST request to token endpoint
* @param authority
* @param request
*/
async executeTokenRequest(authority, request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientExecuteTokenRequest, request.correlationId);
const queryParametersString = this.createTokenQueryParameters(request);
const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), PerformanceEvents.AuthClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);
let ccsCredential = undefined;
if (request.clientInfo) {
try {
const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode);
ccsCredential = {
credential: `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
type: CcsCredentialType.HOME_ACCOUNT_ID,
};
}
catch (e) {
this.logger.verbose("Could not parse client info for CCS Header: " + e);
}
}
const headers = this.createTokenRequestHeaders(ccsCredential || request.ccsCredential);
const thumbprint = {
clientId: request.tokenBodyParameters?.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,
};
return invokeAsync(this.executePostToTokenEndpoint.bind(this), PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint);
}
/**
* Generates a map for all the params to be sent to the service
* @param request
*/
async createTokenRequestBody(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientCreateTokenRequestBody, request.correlationId);
const parameterBuilder = new RequestParameterBuilder(request.correlationId, this.performanceClient);
parameterBuilder.addClientId(request.embeddedClientId ||
request.tokenBodyParameters?.[CLIENT_ID] ||
this.config.authOptions.clientId);
/*
* For hybrid spa flow, there will be a code but no verifier
* In this scenario, don't include redirect uri as auth code will not be bound to redirect URI
*/
if (!this.includeRedirectUri) {
// Just validate
RequestValidator.validateRedirectUri(request.redirectUri);
}
else {
// Validate and include redirect uri
parameterBuilder.addRedirectUri(request.redirectUri);
}
// Add scope array, parameter builder will add default scopes and dedupe
parameterBuilder.addScopes(request.scopes, true, this.oidcDefaultScopes);
// add code: user set, not validated
parameterBuilder.addAuthorizationCode(request.code);
// Add library metadata
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
// add code_verifier if passed
if (request.codeVerifier) {
parameterBuilder.addCodeVerifier(request.codeVerifier);
}
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
const clientAssertion = this.config.clientCredentials.clientAssertion;
parameterBuilder.addClientAssertion(await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
parameterBuilder.addGrantType(GrantType.AUTHORIZATION_CODE_GRANT);
parameterBuilder.addClientInfo();
if (request.authenticationScheme === AuthenticationScheme.POP) {
const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
let reqCnfData;
if (!request.popKid) {
const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);
reqCnfData = generatedReqCnfData.reqCnfString;
}
else {
reqCnfData = this.cryptoUtils.encodeKid(request.popKid);
}
// SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
parameterBuilder.addPopToken(reqCnfData);
}
else if (request.authenticationScheme === AuthenticationScheme.SSH) {
if (request.sshJwk) {
parameterBuilder.addSshJwk(request.sshJwk);
}
else {
throw createClientConfigurationError(missingSshJwk);
}
}
if (!StringUtils.isEmptyObj(request.claims) ||
(this.config.authOptions.clientCapabilities &&
this.config.authOptions.clientCapabilities.length > 0)) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
let ccsCred = undefined;
if (request.clientInfo) {
try {
const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode);
ccsCred = {
credential: `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`,
type: CcsCredentialType.HOME_ACCOUNT_ID,
};
}
catch (e) {
this.logger.verbose("Could not parse client info for CCS Header: " + e);
}
}
else {
ccsCred = request.ccsCredential;
}
// Adds these as parameters in the request instead of headers to prevent CORS preflight request
if (this.config.systemOptions.preventCorsPreflight && ccsCred) {
switch (ccsCred.type) {
case CcsCredentialType.HOME_ACCOUNT_ID:
try {
const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.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(ccsCred.credential);
break;
}
}
if (request.embeddedClientId) {
parameterBuilder.addBrokerParameters({
brokerClientId: this.config.authOptions.clientId,
brokerRedirectUri: this.config.authOptions.redirectUri,
});
}
if (request.tokenBodyParameters) {
parameterBuilder.addExtraQueryParameters(request.tokenBodyParameters);
}
// Add hybrid spa parameters if not already provided
if (request.enableSpaAuthorizationCode &&
(!request.tokenBodyParameters ||
!request.tokenBodyParameters[RETURN_SPA_CODE])) {
parameterBuilder.addExtraQueryParameters({
[RETURN_SPA_CODE]: "1",
});
}
return parameterBuilder.createQueryString();
}
/**
* This API validates the `AuthorizationCodeUrlRequest` and creates a URL
* @param request
*/
async createAuthCodeUrlQueryString(request) {
// generate the correlationId if not set by the user and add
const correlationId = request.correlationId ||
this.config.cryptoInterface.createNewGuid();
this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientCreateQueryString, correlationId);
const parameterBuilder = new RequestParameterBuilder(correlationId, this.performanceClient);
parameterBuilder.addClientId(request.embeddedClientId ||
request.extraQueryParameters?.[CLIENT_ID] ||
this.config.authOptions.clientId);
const requestScopes = [
...(request.scopes || []),
...(request.extraScopesToConsent || []),
];
parameterBuilder.addScopes(requestScopes, true, this.oidcDefaultScopes);
// validate the redirectUri (to be a non null value)
parameterBuilder.addRedirectUri(request.redirectUri);
parameterBuilder.addCorrelationId(correlationId);
// add response_mode. If not passed in it defaults to query.
parameterBuilder.addResponseMode(request.responseMode);
// add response_type = code
parameterBuilder.addResponseTypeCode();
// add library info parameters
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
if (!isOidcProtocolMode(this.config)) {
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
}
// add client_info=1
parameterBuilder.addClientInfo();
if (request.codeChallenge && request.codeChallengeMethod) {
parameterBuilder.addCodeChallengeParams(request.codeChallenge, request.codeChallengeMethod);
}
if (request.prompt) {
parameterBuilder.addPrompt(request.prompt);
}
if (request.domainHint) {
parameterBuilder.addDomainHint(request.domainHint);
this.performanceClient?.addFields({ domainHintFromRequest: true }, correlationId);
}
this.performanceClient?.addFields({ prompt: request.prompt }, correlationId);
// Add sid or loginHint with preference for login_hint claim (in request) -> sid -> loginHint (upn/email) -> username of AccountInfo object
if (request.prompt !== PromptValue.SELECT_ACCOUNT) {
// AAD will throw if prompt=select_account is passed with an account hint
if (request.sid && request.prompt === PromptValue.NONE) {
// SessionID is only used in silent calls
this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request");
parameterBuilder.addSid(request.sid);
this.performanceClient?.addFields({ sidFromRequest: true }, correlationId);
}
else if (request.account) {
const accountSid = this.extractAccountSid(request.account);
let accountLoginHintClaim = this.extractLoginHint(request.account);
if (accountLoginHintClaim && request.domainHint) {
this.logger.warning(`AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint`);
accountLoginHintClaim = null;
}
// If login_hint claim is present, use it over sid/username
if (accountLoginHintClaim) {
this.logger.verbose("createAuthCodeUrlQueryString: login_hint claim present on account");
parameterBuilder.addLoginHint(accountLoginHintClaim);
this.performanceClient?.addFields({ loginHintFromClaim: true }, correlationId);
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
}
}
else if (accountSid && request.prompt === PromptValue.NONE) {
/*
* If account and loginHint are provided, we will check account first for sid before adding loginHint
* SessionId is only used in silent calls
*/
this.logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account");
parameterBuilder.addSid(accountSid);
this.performanceClient?.addFields({ sidFromClaim: true }, correlationId);
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
}
}
else if (request.loginHint) {
this.logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from request");
parameterBuilder.addLoginHint(request.loginHint);
parameterBuilder.addCcsUpn(request.loginHint);
this.performanceClient?.addFields({ loginHintFromRequest: true }, correlationId);
}
else if (request.account.username) {
// Fallback to account username if provided
this.logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from account");
parameterBuilder.addLoginHint(request.account.username);
this.performanceClient?.addFields({ loginHintFromUpn: true }, correlationId);
try {
const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId);
parameterBuilder.addCcsOid(clientInfo);
}
catch (e) {
this.logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header");
}
}
}
else if (request.loginHint) {
this.logger.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request");
parameterBuilder.addLoginHint(request.loginHint);
parameterBuilder.addCcsUpn(request.loginHint);
this.performanceClient?.addFields({ loginHintFromRequest: true }, correlationId);
}
}
else {
this.logger.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints");
}
if (request.nonce) {
parameterBuilder.addNonce(request.nonce);
}
if (request.state) {
parameterBuilder.addState(request.state);
}
if (request.claims ||
(this.config.authOptions.clientCapabilities &&
this.config.authOptions.clientCapabilities.length > 0)) {
parameterBuilder.addClaims(request.claims, this.config.authOptions.clientCapabilities);
}
if (request.embeddedClientId) {
parameterBuilder.addBrokerParameters({
brokerClientId: this.config.authOptions.clientId,
brokerRedirectUri: this.config.authOptions.redirectUri,
});
}
this.addExtraQueryParams(request, parameterBuilder);
if (request.platformBroker) {
// signal ests that this is a WAM call
parameterBuilder.addNativeBroker();
// pass the req_cnf for POP
if (request.authenticationScheme === AuthenticationScheme.POP) {
const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils);
// req_cnf is always sent as a string for SPAs
let reqCnfData;
if (!request.popKid) {
const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);
reqCnfData = generatedReqCnfData.reqCnfString;
}
else {
reqCnfData = this.cryptoUtils.encodeKid(request.popKid);
}
parameterBuilder.addPopToken(reqCnfData);
}
}
return parameterBuilder.createQueryString();
}
/**
* This API validates the `EndSessionRequest` and creates a URL
* @param request
*/
createLogoutUrlQueryString(request) {
const parameterBuilder = new RequestParameterBuilder(request.correlationId, this.performanceClient);
if (request.postLogoutRedirectUri) {
parameterBuilder.addPostLogoutRedirectUri(request.postLogoutRedirectUri);
}
if (request.correlationId) {
parameterBuilder.addCorrelationId(request.correlationId);
}
if (request.idTokenHint) {
parameterBuilder.addIdTokenHint(request.idTokenHint);
}
if (request.state) {
parameterBuilder.addState(request.state);
}
if (request.logoutHint) {
parameterBuilder.addLogoutHint(request.logoutHint);
}
this.addExtraQueryParams(request, parameterBuilder);
return parameterBuilder.createQueryString();
}
addExtraQueryParams(request, parameterBuilder) {
const hasRequestInstanceAware = request.extraQueryParameters &&
request.extraQueryParameters.hasOwnProperty("instance_aware");
// Set instance_aware flag if config auth param is set
if (!hasRequestInstanceAware && this.config.authOptions.instanceAware) {
request.extraQueryParameters = request.extraQueryParameters || {};
request.extraQueryParameters["instance_aware"] = "true";
}
if (request.extraQueryParameters) {
parameterBuilder.addExtraQueryParameters(request.extraQueryParameters);
}
}
/**
* Helper to get sid from account. Returns null if idTokenClaims are not present or sid is not present.
* @param account
*/
extractAccountSid(account) {
return account.idTokenClaims?.sid || null;
}
extractLoginHint(account) {
return account.idTokenClaims?.login_hint || null;
}
}
export { AuthorizationCodeClient };
//# sourceMappingURL=AuthorizationCodeClient.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,59 @@
import { ClientConfiguration, CommonClientConfiguration } from "../config/ClientConfiguration.js";
import { INetworkModule, NetworkRequestOptions } from "../network/INetworkModule.js";
import { NetworkResponse } from "../network/NetworkResponse.js";
import { ICrypto } from "../crypto/ICrypto.js";
import { Authority } from "../authority/Authority.js";
import { Logger } from "../logger/Logger.js";
import { ServerAuthorizationTokenResponse } from "../response/ServerAuthorizationTokenResponse.js";
import { CacheManager } from "../cache/CacheManager.js";
import { ServerTelemetryManager } from "../telemetry/server/ServerTelemetryManager.js";
import { RequestThumbprint } from "../network/RequestThumbprint.js";
import { CcsCredential } from "../account/CcsCredential.js";
import { IPerformanceClient } from "../telemetry/performance/IPerformanceClient.js";
import { BaseAuthRequest } from "../request/BaseAuthRequest.js";
/**
* Base application class which will construct requests to send to and handle responses from the Microsoft STS using the authorization code flow.
* @internal
*/
export declare abstract class BaseClient {
logger: Logger;
protected config: CommonClientConfiguration;
protected cryptoUtils: ICrypto;
protected cacheManager: CacheManager;
protected networkClient: INetworkModule;
protected serverTelemetryManager: ServerTelemetryManager | null;
authority: Authority;
protected performanceClient?: IPerformanceClient;
protected constructor(configuration: ClientConfiguration, performanceClient?: IPerformanceClient);
/**
* Creates default headers for requests to token endpoint
*/
protected createTokenRequestHeaders(ccsCred?: CcsCredential): Record<string, string>;
/**
* Http post to token endpoint
* @param tokenEndpoint
* @param queryString
* @param headers
* @param thumbprint
*/
protected executePostToTokenEndpoint(tokenEndpoint: string, queryString: string, headers: Record<string, string>, thumbprint: RequestThumbprint, correlationId: string, queuedEvent?: string): Promise<NetworkResponse<ServerAuthorizationTokenResponse>>;
/**
* Wraps sendPostRequestAsync with necessary preflight and postflight logic
* @param thumbprint - Request thumbprint for throttling
* @param tokenEndpoint - Endpoint to make the POST to
* @param options - Body and Headers to include on the POST request
* @param correlationId - CorrelationId for telemetry
*/
sendPostRequest<T extends ServerAuthorizationTokenResponse>(thumbprint: RequestThumbprint, tokenEndpoint: string, options: NetworkRequestOptions, correlationId: string): Promise<NetworkResponse<T>>;
/**
* Updates the authority object of the client. Endpoint discovery must be completed.
* @param updatedAuthority
*/
updateAuthority(cloudInstanceHostname: string, correlationId: string): Promise<void>;
/**
* Creates query string for the /token request
* @param request
*/
createTokenQueryParameters(request: BaseAuthRequest): string;
}
//# sourceMappingURL=BaseClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BaseClient.d.ts","sourceRoot":"","sources":["../../src/client/BaseClient.ts"],"names":[],"mappings":"AAKA,OAAO,EACH,mBAAmB,EAEnB,yBAAyB,EAC5B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EACH,cAAc,EACd,qBAAqB,EACxB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAChE,OAAO,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAE7C,OAAO,EAAE,gCAAgC,EAAE,MAAM,iDAAiD,CAAC;AACnG,OAAO,EAAE,YAAY,EAAE,MAAM,0BAA0B,CAAC;AACxD,OAAO,EAAE,sBAAsB,EAAE,MAAM,+CAA+C,CAAC;AACvF,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAEpE,OAAO,EAAE,aAAa,EAAqB,MAAM,6BAA6B,CAAC;AAE/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,gDAAgD,CAAC;AAEpF,OAAO,EAAE,eAAe,EAAE,MAAM,+BAA+B,CAAC;AAYhE;;;GAGG;AACH,8BAAsB,UAAU;IAErB,MAAM,EAAE,MAAM,CAAC;IAGtB,SAAS,CAAC,MAAM,EAAE,yBAAyB,CAAC;IAG5C,SAAS,CAAC,WAAW,EAAE,OAAO,CAAC;IAG/B,SAAS,CAAC,YAAY,EAAE,YAAY,CAAC;IAGrC,SAAS,CAAC,aAAa,EAAE,cAAc,CAAC;IAGxC,SAAS,CAAC,sBAAsB,EAAE,sBAAsB,GAAG,IAAI,CAAC;IAGzD,SAAS,EAAE,SAAS,CAAC;IAG5B,SAAS,CAAC,iBAAiB,CAAC,EAAE,kBAAkB,CAAC;IAEjD,SAAS,aACL,aAAa,EAAE,mBAAmB,EAClC,iBAAiB,CAAC,EAAE,kBAAkB;IA2B1C;;OAEG;IACH,SAAS,CAAC,yBAAyB,CAC/B,OAAO,CAAC,EAAE,aAAa,GACxB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC;IA8BzB;;;;;;OAMG;cACa,0BAA0B,CACtC,aAAa,EAAE,MAAM,EACrB,WAAW,EAAE,MAAM,EACnB,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,EAC/B,UAAU,EAAE,iBAAiB,EAC7B,aAAa,EAAE,MAAM,EACrB,WAAW,CAAC,EAAE,MAAM,GACrB,OAAO,CAAC,eAAe,CAAC,gCAAgC,CAAC,CAAC;IA4B7D;;;;;;OAMG;IACG,eAAe,CAAC,CAAC,SAAS,gCAAgC,EAC5D,UAAU,EAAE,iBAAiB,EAC7B,aAAa,EAAE,MAAM,EACrB,OAAO,EAAE,qBAAqB,EAC9B,aAAa,EAAE,MAAM,GACtB,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC,CAAC;IA+D9B;;;OAGG;IACG,eAAe,CACjB,qBAAqB,EAAE,MAAM,EAC7B,aAAa,EAAE,MAAM,GACtB,OAAO,CAAC,IAAI,CAAC;IAkBhB;;;OAGG;IACH,0BAA0B,CAAC,OAAO,EAAE,eAAe,GAAG,MAAM;CAuB/D"}

View File

@@ -0,0 +1,168 @@
/*! @azure/msal-common v15.1.1 2025-02-05 */
'use strict';
import { buildClientConfiguration } from '../config/ClientConfiguration.mjs';
import { Logger } from '../logger/Logger.mjs';
import { HeaderNames, Constants } from '../utils/Constants.mjs';
import { name, version } from '../packageMetadata.mjs';
import { CcsCredentialType } from '../account/CcsCredential.mjs';
import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs';
import { RequestParameterBuilder } from '../request/RequestParameterBuilder.mjs';
import { createDiscoveredInstance } from '../authority/AuthorityFactory.mjs';
import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs';
import { ThrottlingUtils } from '../network/ThrottlingUtils.mjs';
import { AuthError } from '../error/AuthError.mjs';
import { createClientAuthError } from '../error/ClientAuthError.mjs';
import { NetworkError } from '../error/NetworkError.mjs';
import { invokeAsync } from '../utils/FunctionWrappers.mjs';
import { networkError } from '../error/ClientAuthErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/**
* Base application class which will construct requests to send to and handle responses from the Microsoft STS using the authorization code flow.
* @internal
*/
class BaseClient {
constructor(configuration, performanceClient) {
// Set the configuration
this.config = buildClientConfiguration(configuration);
// Initialize the logger
this.logger = new Logger(this.config.loggerOptions, name, version);
// Initialize crypto
this.cryptoUtils = this.config.cryptoInterface;
// Initialize storage interface
this.cacheManager = this.config.storageInterface;
// Set the network interface
this.networkClient = this.config.networkInterface;
// Set TelemetryManager
this.serverTelemetryManager = this.config.serverTelemetryManager;
// set Authority
this.authority = this.config.authOptions.authority;
// set performance telemetry client
this.performanceClient = performanceClient;
}
/**
* Creates default headers for requests to token endpoint
*/
createTokenRequestHeaders(ccsCred) {
const headers = {};
headers[HeaderNames.CONTENT_TYPE] = Constants.URL_FORM_CONTENT_TYPE;
if (!this.config.systemOptions.preventCorsPreflight && ccsCred) {
switch (ccsCred.type) {
case CcsCredentialType.HOME_ACCOUNT_ID:
try {
const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential);
headers[HeaderNames.CCS_HEADER] = `Oid:${clientInfo.uid}@${clientInfo.utid}`;
}
catch (e) {
this.logger.verbose("Could not parse home account ID for CCS Header: " +
e);
}
break;
case CcsCredentialType.UPN:
headers[HeaderNames.CCS_HEADER] = `UPN: ${ccsCred.credential}`;
break;
}
}
return headers;
}
/**
* Http post to token endpoint
* @param tokenEndpoint
* @param queryString
* @param headers
* @param thumbprint
*/
async executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, queuedEvent) {
if (queuedEvent) {
this.performanceClient?.addQueueMeasurement(queuedEvent, correlationId);
}
const response = await this.sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers: headers }, correlationId);
if (this.config.serverTelemetryManager &&
response.status < 500 &&
response.status !== 429) {
// Telemetry data successfully logged by server, clear Telemetry cache
this.config.serverTelemetryManager.clearTelemetryCache();
}
return response;
}
/**
* Wraps sendPostRequestAsync with necessary preflight and postflight logic
* @param thumbprint - Request thumbprint for throttling
* @param tokenEndpoint - Endpoint to make the POST to
* @param options - Body and Headers to include on the POST request
* @param correlationId - CorrelationId for telemetry
*/
async sendPostRequest(thumbprint, tokenEndpoint, options, correlationId) {
ThrottlingUtils.preProcess(this.cacheManager, thumbprint);
let response;
try {
response = await invokeAsync((this.networkClient.sendPostRequestAsync.bind(this.networkClient)), PerformanceEvents.NetworkClientSendPostRequestAsync, this.logger, this.performanceClient, correlationId)(tokenEndpoint, options);
const responseHeaders = response.headers || {};
this.performanceClient?.addFields({
refreshTokenSize: response.body.refresh_token?.length || 0,
httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",
requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "",
}, correlationId);
}
catch (e) {
if (e instanceof NetworkError) {
const responseHeaders = e.responseHeaders;
if (responseHeaders) {
this.performanceClient?.addFields({
httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "",
requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] ||
"",
contentTypeHeader: responseHeaders[HeaderNames.CONTENT_TYPE] ||
undefined,
contentLengthHeader: responseHeaders[HeaderNames.CONTENT_LENGTH] ||
undefined,
httpStatus: e.httpStatus,
}, correlationId);
}
throw e.error;
}
if (e instanceof AuthError) {
throw e;
}
else {
throw createClientAuthError(networkError);
}
}
ThrottlingUtils.postProcess(this.cacheManager, thumbprint, response);
return response;
}
/**
* Updates the authority object of the client. Endpoint discovery must be completed.
* @param updatedAuthority
*/
async updateAuthority(cloudInstanceHostname, correlationId) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.UpdateTokenEndpointAuthority, correlationId);
const cloudInstanceAuthorityUri = `https://${cloudInstanceHostname}/${this.authority.tenant}/`;
const cloudInstanceAuthority = await createDiscoveredInstance(cloudInstanceAuthorityUri, this.networkClient, this.cacheManager, this.authority.options, this.logger, correlationId, this.performanceClient);
this.authority = cloudInstanceAuthority;
}
/**
* Creates query string for the /token request
* @param request
*/
createTokenQueryParameters(request) {
const parameterBuilder = new RequestParameterBuilder(request.correlationId, this.performanceClient);
if (request.embeddedClientId) {
parameterBuilder.addBrokerParameters({
brokerClientId: this.config.authOptions.clientId,
brokerRedirectUri: this.config.authOptions.redirectUri,
});
}
if (request.tokenQueryParameters) {
parameterBuilder.addExtraQueryParameters(request.tokenQueryParameters);
}
parameterBuilder.addCorrelationId(request.correlationId);
return parameterBuilder.createQueryString();
}
}
export { BaseClient };
//# sourceMappingURL=BaseClient.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"BaseClient.mjs","sources":["../../src/client/BaseClient.ts"],"sourcesContent":[null],"names":["ClientAuthErrorCodes.networkError"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;;;AAGG;AAqCH;;;AAGG;MACmB,UAAU,CAAA;IAyB5B,WACI,CAAA,aAAkC,EAClC,iBAAsC,EAAA;;AAGtC,QAAA,IAAI,CAAC,MAAM,GAAG,wBAAwB,CAAC,aAAa,CAAC,CAAC;;AAGtD,QAAA,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,aAAa,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;;QAGnE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,MAAM,CA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+1,36 @@
import { ClientConfiguration } from "../config/ClientConfiguration.js";
import { BaseClient } from "./BaseClient.js";
import { CommonRefreshTokenRequest } from "../request/CommonRefreshTokenRequest.js";
import { AuthenticationResult } from "../response/AuthenticationResult.js";
import { CommonSilentFlowRequest } from "../request/CommonSilentFlowRequest.js";
import { IPerformanceClient } from "../telemetry/performance/IPerformanceClient.js";
/**
* OAuth2.0 refresh token client
* @internal
*/
export declare class RefreshTokenClient extends BaseClient {
constructor(configuration: ClientConfiguration, performanceClient?: IPerformanceClient);
acquireToken(request: CommonRefreshTokenRequest): Promise<AuthenticationResult>;
/**
* Gets cached refresh token and attaches to request, then calls acquireToken API
* @param request
*/
acquireTokenByRefreshToken(request: CommonSilentFlowRequest): Promise<AuthenticationResult>;
/**
* makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached
* @param request
*/
private acquireTokenWithCachedRefreshToken;
/**
* Constructs the network message and makes a NW call to the underlying secure token service
* @param request
* @param authority
*/
private executeTokenRequest;
/**
* Helper function to create the token request body
* @param request
*/
private createTokenRequestBody;
}
//# sourceMappingURL=RefreshTokenClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"RefreshTokenClient.d.ts","sourceRoot":"","sources":["../../src/client/RefreshTokenClient.ts"],"names":[],"mappings":"AAKA,OAAO,EACH,mBAAmB,EAEtB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AAYpF,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAK3E,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAoBhF,OAAO,EAAE,kBAAkB,EAAE,MAAM,gDAAgD,CAAC;AAQpF;;;GAGG;AACH,qBAAa,kBAAmB,SAAQ,UAAU;gBAE1C,aAAa,EAAE,mBAAmB,EAClC,iBAAiB,CAAC,EAAE,kBAAkB;IAI7B,YAAY,CACrB,OAAO,EAAE,yBAAyB,GACnC,OAAO,CAAC,oBAAoB,CAAC;IA8ChC;;;OAGG;IACU,0BAA0B,CACnC,OAAO,EAAE,uBAAuB,GACjC,OAAO,CAAC,oBAAoB,CAAC;IAsEhC;;;OAGG;YACW,kCAAkC;IAyFhD;;;;OAIG;YACW,mBAAmB;IAuDjC;;;OAGG;YACW,sBAAsB;CAyJvC"}

View File

@@ -0,0 +1,249 @@
/*! @azure/msal-common v15.1.1 2025-02-05 */
'use strict';
import { isOidcProtocolMode } from '../config/ClientConfiguration.mjs';
import { BaseClient } from './BaseClient.mjs';
import { RequestParameterBuilder } from '../request/RequestParameterBuilder.mjs';
import { GrantType, AuthenticationScheme, HeaderNames, Errors } from '../utils/Constants.mjs';
import { CLIENT_ID } from '../constants/AADServerParamKeys.mjs';
import { ResponseHandler } from '../response/ResponseHandler.mjs';
import { PopTokenGenerator } from '../crypto/PopTokenGenerator.mjs';
import { StringUtils } from '../utils/StringUtils.mjs';
import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs';
import { createClientAuthError } from '../error/ClientAuthError.mjs';
import { ServerError } from '../error/ServerError.mjs';
import { nowSeconds, isTokenExpired } from '../utils/TimeUtils.mjs';
import { UrlString } from '../url/UrlString.mjs';
import { CcsCredentialType } from '../account/CcsCredential.mjs';
import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs';
import { createInteractionRequiredAuthError, InteractionRequiredAuthError } from '../error/InteractionRequiredAuthError.mjs';
import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs';
import { invokeAsync, invoke } from '../utils/FunctionWrappers.mjs';
import { generateCredentialKey } from '../cache/utils/CacheHelpers.mjs';
import { getClientAssertion } from '../utils/ClientAssertionUtils.mjs';
import { tokenRequestEmpty, missingSshJwk } from '../error/ClientConfigurationErrorCodes.mjs';
import { noAccountInSilentRequest } from '../error/ClientAuthErrorCodes.mjs';
import { noTokensFound, refreshTokenExpired, badToken } from '../error/InteractionRequiredAuthErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
const DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS = 300; // 5 Minutes
/**
* OAuth2.0 refresh token client
* @internal
*/
class RefreshTokenClient extends BaseClient {
constructor(configuration, performanceClient) {
super(configuration, performanceClient);
}
async acquireToken(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId);
const reqTimestamp = nowSeconds();
const response = await invokeAsync(this.executeTokenRequest.bind(this), PerformanceEvents.RefreshTokenClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(request, this.authority);
// Retrieve requestId from response headers
const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID];
const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin);
responseHandler.validateTokenResponse(response.body);
return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), PerformanceEvents.HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, undefined, undefined, true, request.forceCache, requestId);
}
/**
* Gets cached refresh token and attaches to request, then calls acquireToken API
* @param request
*/
async acquireTokenByRefreshToken(request) {
// Cannot renew token if no request object is given.
if (!request) {
throw createClientConfigurationError(tokenRequestEmpty);
}
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenByRefreshToken, request.correlationId);
// We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
if (!request.account) {
throw createClientAuthError(noAccountInSilentRequest);
}
// try checking if FOCI is enabled for the given application
const isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment);
// if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest
if (isFOCI) {
try {
return await invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, true);
}
catch (e) {
const noFamilyRTInCache = e instanceof InteractionRequiredAuthError &&
e.errorCode ===
noTokensFound;
const 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 invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false);
// throw in all other cases
}
else {
throw e;
}
}
}
// fall back to application refresh token acquisition
return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false);
}
/**
* makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached
* @param request
*/
async acquireTokenWithCachedRefreshToken(request, foci) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId);
// fetches family RT or application RT based on FOCI value
const refreshToken = invoke(this.cacheManager.getRefreshToken.bind(this.cacheManager), PerformanceEvents.CacheManagerGetRefreshToken, this.logger, this.performanceClient, request.correlationId)(request.account, foci, undefined, this.performanceClient, request.correlationId);
if (!refreshToken) {
throw createInteractionRequiredAuthError(noTokensFound);
}
if (refreshToken.expiresOn &&
isTokenExpired(refreshToken.expiresOn, request.refreshTokenExpirationOffsetSeconds ||
DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS)) {
this.performanceClient?.addFields({ rtExpiresOnMs: Number(refreshToken.expiresOn) }, request.correlationId);
throw createInteractionRequiredAuthError(refreshTokenExpired);
}
// attach cached RT size to the current measurement
const refreshTokenRequest = {
...request,
refreshToken: refreshToken.secret,
authenticationScheme: request.authenticationScheme || AuthenticationScheme.BEARER,
ccsCredential: {
credential: request.account.homeAccountId,
type: CcsCredentialType.HOME_ACCOUNT_ID,
},
};
try {
return await invokeAsync(this.acquireToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(refreshTokenRequest);
}
catch (e) {
if (e instanceof InteractionRequiredAuthError) {
this.performanceClient?.addFields({ rtExpiresOnMs: Number(refreshToken.expiresOn) }, request.correlationId);
if (e.subError === badToken) {
// Remove bad refresh token from cache
this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache");
const badRefreshTokenKey = generateCredentialKey(refreshToken);
this.cacheManager.removeRefreshToken(badRefreshTokenKey);
}
}
throw e;
}
}
/**
* Constructs the network message and makes a NW call to the underlying secure token service
* @param request
* @param authority
*/
async executeTokenRequest(request, authority) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId);
const queryParametersString = this.createTokenQueryParameters(request);
const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString);
const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request);
const headers = this.createTokenRequestHeaders(request.ccsCredential);
const thumbprint = {
clientId: request.tokenBodyParameters?.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,
};
return invokeAsync(this.executePostToTokenEndpoint.bind(this), PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint);
}
/**
* Helper function to create the token request body
* @param request
*/
async createTokenRequestBody(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, request.correlationId);
const correlationId = request.correlationId;
const parameterBuilder = new RequestParameterBuilder(correlationId, this.performanceClient);
parameterBuilder.addClientId(request.embeddedClientId ||
request.tokenBodyParameters?.[CLIENT_ID] ||
this.config.authOptions.clientId);
if (request.redirectUri) {
parameterBuilder.addRedirectUri(request.redirectUri);
}
parameterBuilder.addScopes(request.scopes, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes);
parameterBuilder.addGrantType(GrantType.REFRESH_TOKEN_GRANT);
parameterBuilder.addClientInfo();
parameterBuilder.addLibraryInfo(this.config.libraryInfo);
parameterBuilder.addApplicationTelemetry(this.config.telemetry.application);
parameterBuilder.addThrottling();
if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) {
parameterBuilder.addServerTelemetry(this.serverTelemetryManager);
}
parameterBuilder.addRefreshToken(request.refreshToken);
if (this.config.clientCredentials.clientSecret) {
parameterBuilder.addClientSecret(this.config.clientCredentials.clientSecret);
}
if (this.config.clientCredentials.clientAssertion) {
const clientAssertion = this.config.clientCredentials.clientAssertion;
parameterBuilder.addClientAssertion(await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri));
parameterBuilder.addClientAssertionType(clientAssertion.assertionType);
}
if (request.authenticationScheme === AuthenticationScheme.POP) {
const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient);
let reqCnfData;
if (!request.popKid) {
const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger);
reqCnfData = generatedReqCnfData.reqCnfString;
}
else {
reqCnfData = this.cryptoUtils.encodeKid(request.popKid);
}
// SPA PoP requires full Base64Url encoded req_cnf string (unhashed)
parameterBuilder.addPopToken(reqCnfData);
}
else if (request.authenticationScheme === AuthenticationScheme.SSH) {
if (request.sshJwk) {
parameterBuilder.addSshJwk(request.sshJwk);
}
else {
throw createClientConfigurationError(missingSshJwk);
}
}
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 {
const 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;
}
}
if (request.embeddedClientId) {
parameterBuilder.addBrokerParameters({
brokerClientId: this.config.authOptions.clientId,
brokerRedirectUri: this.config.authOptions.redirectUri,
});
}
if (request.tokenBodyParameters) {
parameterBuilder.addExtraQueryParameters(request.tokenBodyParameters);
}
return parameterBuilder.createQueryString();
}
}
export { RefreshTokenClient };
//# sourceMappingURL=RefreshTokenClient.mjs.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,22 @@
import { BaseClient } from "./BaseClient.js";
import { ClientConfiguration } from "../config/ClientConfiguration.js";
import { CommonSilentFlowRequest } from "../request/CommonSilentFlowRequest.js";
import { AuthenticationResult } from "../response/AuthenticationResult.js";
import { CacheOutcome } from "../utils/Constants.js";
import { IPerformanceClient } from "../telemetry/performance/IPerformanceClient.js";
/** @internal */
export declare class SilentFlowClient extends BaseClient {
constructor(configuration: ClientConfiguration, performanceClient?: IPerformanceClient);
/**
* Retrieves token from cache or throws an error if it must be refreshed.
* @param request
*/
acquireCachedToken(request: CommonSilentFlowRequest): Promise<[AuthenticationResult, CacheOutcome]>;
private setCacheOutcome;
/**
* Helper function to build response object from the CacheRecord
* @param cacheRecord
*/
private generateResultFromCacheRecord;
}
//# sourceMappingURL=SilentFlowClient.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"SilentFlowClient.d.ts","sourceRoot":"","sources":["../../src/client/SilentFlowClient.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AACvE,OAAO,EAAE,uBAAuB,EAAE,MAAM,uCAAuC,CAAC;AAChF,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAQ3E,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,kBAAkB,EAAE,MAAM,gDAAgD,CAAC;AAQpF,gBAAgB;AAChB,qBAAa,gBAAiB,SAAQ,UAAU;gBAExC,aAAa,EAAE,mBAAmB,EAClC,iBAAiB,CAAC,EAAE,kBAAkB;IAK1C;;;OAGG;IACG,kBAAkB,CACpB,OAAO,EAAE,uBAAuB,GACjC,OAAO,CAAC,CAAC,oBAAoB,EAAE,YAAY,CAAC,CAAC;IA+GhD,OAAO,CAAC,eAAe;IAkBvB;;;OAGG;YACW,6BAA6B;CAqC9C"}

View File

@@ -0,0 +1,112 @@
/*! @azure/msal-common v15.1.1 2025-02-05 */
'use strict';
import { BaseClient } from './BaseClient.mjs';
import { wasClockTurnedBack, isTokenExpired } from '../utils/TimeUtils.mjs';
import { createClientAuthError } from '../error/ClientAuthError.mjs';
import { ResponseHandler } from '../response/ResponseHandler.mjs';
import { CacheOutcome } from '../utils/Constants.mjs';
import { StringUtils } from '../utils/StringUtils.mjs';
import { extractTokenClaims, checkMaxAge } from '../account/AuthToken.mjs';
import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs';
import { invokeAsync } from '../utils/FunctionWrappers.mjs';
import { getTenantFromAuthorityString } from '../authority/Authority.mjs';
import { tokenRefreshRequired, noAccountInSilentRequest, authTimeNotFound } from '../error/ClientAuthErrorCodes.mjs';
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
/** @internal */
class SilentFlowClient extends BaseClient {
constructor(configuration, performanceClient) {
super(configuration, performanceClient);
}
/**
* Retrieves token from cache or throws an error if it must be refreshed.
* @param request
*/
async acquireCachedToken(request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.SilentFlowClientAcquireCachedToken, request.correlationId);
let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE;
if (request.forceRefresh ||
(!this.config.cacheOptions.claimsBasedCachingEnabled &&
!StringUtils.isEmptyObj(request.claims))) {
// Must refresh due to present force_refresh flag.
this.setCacheOutcome(CacheOutcome.FORCE_REFRESH_OR_CLAIMS, request.correlationId);
throw createClientAuthError(tokenRefreshRequired);
}
// We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases
if (!request.account) {
throw createClientAuthError(noAccountInSilentRequest);
}
const requestTenantId = request.account.tenantId ||
getTenantFromAuthorityString(request.authority);
const tokenKeys = this.cacheManager.getTokenKeys();
const cachedAccessToken = this.cacheManager.getAccessToken(request.account, request, tokenKeys, requestTenantId, this.performanceClient, request.correlationId);
if (!cachedAccessToken) {
// must refresh due to non-existent access_token
this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId);
throw createClientAuthError(tokenRefreshRequired);
}
else if (wasClockTurnedBack(cachedAccessToken.cachedAt) ||
isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) {
// must refresh due to the expires_in value
this.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED, request.correlationId);
throw createClientAuthError(tokenRefreshRequired);
}
else if (cachedAccessToken.refreshOn &&
isTokenExpired(cachedAccessToken.refreshOn, 0)) {
// must refresh (in the background) due to the refresh_in value
lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED;
// don't throw ClientAuthError.createRefreshRequiredError(), return cached token instead
}
const environment = request.authority || this.authority.getPreferredCache();
const cacheRecord = {
account: this.cacheManager.readAccountFromCache(request.account),
accessToken: cachedAccessToken,
idToken: this.cacheManager.getIdToken(request.account, tokenKeys, requestTenantId, this.performanceClient, request.correlationId),
refreshToken: null,
appMetadata: this.cacheManager.readAppMetadataFromCache(environment),
};
this.setCacheOutcome(lastCacheOutcome, request.correlationId);
if (this.config.serverTelemetryManager) {
this.config.serverTelemetryManager.incrementCacheHits();
}
return [
await invokeAsync(this.generateResultFromCacheRecord.bind(this), PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord, this.logger, this.performanceClient, request.correlationId)(cacheRecord, request),
lastCacheOutcome,
];
}
setCacheOutcome(cacheOutcome, correlationId) {
this.serverTelemetryManager?.setCacheOutcome(cacheOutcome);
this.performanceClient?.addFields({
cacheOutcome: cacheOutcome,
}, correlationId);
if (cacheOutcome !== CacheOutcome.NOT_APPLICABLE) {
this.logger.info(`Token refresh is required due to cache outcome: ${cacheOutcome}`);
}
}
/**
* Helper function to build response object from the CacheRecord
* @param cacheRecord
*/
async generateResultFromCacheRecord(cacheRecord, request) {
this.performanceClient?.addQueueMeasurement(PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord, request.correlationId);
let idTokenClaims;
if (cacheRecord.idToken) {
idTokenClaims = extractTokenClaims(cacheRecord.idToken.secret, this.config.cryptoInterface.base64Decode);
}
// token max_age check
if (request.maxAge || request.maxAge === 0) {
const authTime = idTokenClaims?.auth_time;
if (!authTime) {
throw createClientAuthError(authTimeNotFound);
}
checkMaxAge(authTime, request.maxAge);
}
return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, idTokenClaims);
}
}
export { SilentFlowClient };
//# sourceMappingURL=SilentFlowClient.mjs.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"SilentFlowClient.mjs","sources":["../../src/client/SilentFlowClient.ts"],"sourcesContent":[null],"names":["ClientAuthErrorCodes.tokenRefreshRequired","ClientAuthErrorCodes.noAccountInSilentRequest","TimeUtils.wasClockTurnedBack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