wangzhibo
2026-05-09 53418655c061ac26f66058253f39200aced1ab1d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
 
import {
    AADServerParamKeys,
    AccessTokenEntity,
    AccountEntity,
    AccountInfo,
    AuthenticationResult,
    Authority,
    AuthToken,
    ClientAuthErrorCodes,
    ClientConfiguration,
    createClientAuthError,
    CredentialFilter,
    Constants,
    IdTokenEntity,
    RequestParameterBuilder,
    RequestThumbprint,
    ResponseHandler,
    ScopeSet,
    TimeUtils,
    TokenClaims,
    UrlString,
    ClientAssertion,
    getClientAssertion,
    UrlUtils,
} from "@azure/msal-common/node";
import { ApiId } from "../utils/Constants.js";
import { EncodingUtils } from "../utils/EncodingUtils.js";
import { CommonOnBehalfOfRequest } from "../request/CommonOnBehalfOfRequest.js";
import { BaseClient } from "./BaseClient.js";
 
/**
 * On-Behalf-Of client
 * @public
 */
export class OnBehalfOfClient extends BaseClient {
    private scopeSet: ScopeSet;
    private userAssertionHash: string;
 
    constructor(configuration: ClientConfiguration) {
        super(configuration);
    }
 
    /**
     * Public API to acquire tokens with on behalf of flow
     * @param request - developer provided CommonOnBehalfOfRequest
     */
    public async acquireToken(
        request: CommonOnBehalfOfRequest
    ): Promise<AuthenticationResult | null> {
        this.scopeSet = new ScopeSet(request.scopes || []);
 
        // generate the user_assertion_hash for OBOAssertion
        this.userAssertionHash = await this.cryptoUtils.hashString(
            request.oboAssertion
        );
 
        if (request.skipCache || request.claims) {
            return this.executeTokenRequest(
                request,
                this.authority,
                this.userAssertionHash
            );
        }
 
        try {
            return await this.getCachedAuthenticationResult(request);
        } catch (e) {
            // Any failure falls back to interactive request, once we implement distributed cache, we plan to handle `createRefreshRequiredError` to refresh using the RT
            return await this.executeTokenRequest(
                request,
                this.authority,
                this.userAssertionHash
            );
        }
    }
 
    /**
     * 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 - developer provided CommonOnBehalfOfRequest
     */
    private async getCachedAuthenticationResult(
        request: CommonOnBehalfOfRequest
    ): Promise<AuthenticationResult | null> {
        // look in the cache for the access_token which matches the incoming_assertion
        const cachedAccessToken = this.readAccessTokenFromCacheForOBO(
            this.config.authOptions.clientId,
            request
        );
        if (!cachedAccessToken) {
            // Must refresh due to non-existent access_token.
            this.serverTelemetryManager?.setCacheOutcome(
                Constants.CacheOutcome.NO_CACHED_ACCESS_TOKEN
            );
            this.logger.info(
                "SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties.",
                request.correlationId
            );
            throw createClientAuthError(
                ClientAuthErrorCodes.tokenRefreshRequired
            );
        } else if (
            TimeUtils.isTokenExpired(
                cachedAccessToken.expiresOn,
                this.config.systemOptions.tokenRenewalOffsetSeconds
            )
        ) {
            // Access token expired, will need to renewed
            this.serverTelemetryManager?.setCacheOutcome(
                Constants.CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED
            );
            this.logger.info(
                `OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`,
                request.correlationId
            );
            throw createClientAuthError(
                ClientAuthErrorCodes.tokenRefreshRequired
            );
        }
 
        // fetch the idToken from cache
        const cachedIdToken = this.readIdTokenFromCacheForOBO(
            cachedAccessToken.homeAccountId,
            request.correlationId
        );
        let idTokenClaims: TokenClaims | undefined;
        let cachedAccount: AccountEntity | null = null;
        if (cachedIdToken) {
            idTokenClaims = AuthToken.extractTokenClaims(
                cachedIdToken.secret,
                EncodingUtils.base64Decode
            );
            const localAccountId = idTokenClaims.oid || idTokenClaims.sub;
            const accountInfo: AccountInfo = {
                homeAccountId: cachedIdToken.homeAccountId,
                environment: cachedIdToken.environment,
                tenantId: cachedIdToken.realm,
                username: "",
                localAccountId: localAccountId || "",
            };
 
            cachedAccount = this.cacheManager.getAccount(
                this.cacheManager.generateAccountKey(accountInfo),
                request.correlationId
            );
        }
 
        // increment telemetry cache hit counter
        if (this.config.serverTelemetryManager) {
            this.config.serverTelemetryManager.incrementCacheHits();
        }
 
        return ResponseHandler.generateAuthenticationResult(
            this.cryptoUtils,
            this.authority,
            {
                account: cachedAccount,
                accessToken: cachedAccessToken,
                idToken: cachedIdToken,
                refreshToken: null,
                appMetadata: null,
            },
            true,
            request,
            this.performanceClient,
            idTokenClaims
        );
    }
 
    /**
     * 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 atHomeAccountId - account id
     */
    private readIdTokenFromCacheForOBO(
        atHomeAccountId: string,
        correlationId: string
    ): IdTokenEntity | null {
        const idTokenFilter: CredentialFilter = {
            homeAccountId: atHomeAccountId,
            environment:
                this.authority.canonicalAuthorityUrlComponents.HostNameAndPort,
            credentialType: Constants.CredentialType.ID_TOKEN,
            clientId: this.config.authOptions.clientId,
            realm: this.authority.tenant,
        };
 
        const idTokenMap: Map<string, IdTokenEntity> =
            this.cacheManager.getIdTokensByFilter(idTokenFilter, correlationId);
 
        // When acquiring a token on behalf of an application, there might not be an id token in the cache
        if (Object.values(idTokenMap).length < 1) {
            return null;
        }
        return Object.values(idTokenMap)[0] as IdTokenEntity;
    }
 
    /**
     * Fetches the cached access token based on incoming assertion
     * @param clientId - client id
     * @param request - developer provided CommonOnBehalfOfRequest
     */
    private readAccessTokenFromCacheForOBO(
        clientId: string,
        request: CommonOnBehalfOfRequest
    ) {
        const authScheme =
            request.authenticationScheme ||
            Constants.AuthenticationScheme.BEARER;
        /*
         * Distinguish between Bearer and PoP/SSH token cache types
         * Cast to lowercase to handle "bearer" from ADFS
         */
        const credentialType =
            authScheme &&
            authScheme.toLowerCase() !==
                Constants.AuthenticationScheme.BEARER.toLowerCase()
                ? Constants.CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME
                : Constants.CredentialType.ACCESS_TOKEN;
 
        const accessTokenFilter: CredentialFilter = {
            credentialType: credentialType,
            clientId,
            target: ScopeSet.createSearchScopes(this.scopeSet.asArray()),
            tokenType: authScheme,
            keyId: request.sshKid,
            userAssertionHash: this.userAssertionHash,
        };
 
        const accessTokens = this.cacheManager.getAccessTokensByFilter(
            accessTokenFilter,
            request.correlationId
        );
 
        const numAccessTokens = accessTokens.length;
        if (numAccessTokens < 1) {
            return null;
        } else if (numAccessTokens > 1) {
            throw createClientAuthError(
                ClientAuthErrorCodes.multipleMatchingTokens
            );
        }
 
        return accessTokens[0] as AccessTokenEntity;
    }
 
    /**
     * Make a network call to the server requesting credentials
     * @param request - developer provided CommonOnBehalfOfRequest
     * @param authority - authority object
     */
    private async executeTokenRequest(
        request: CommonOnBehalfOfRequest,
        authority: Authority,
        userAssertionHash: string
    ): Promise<AuthenticationResult | null> {
        const queryParametersString = this.createTokenQueryParameters(request);
        const endpoint = UrlString.appendQueryString(
            authority.tokenEndpoint,
            queryParametersString
        );
        const requestBody = await this.createTokenRequestBody(request);
        const headers: Record<string, string> =
            this.createTokenRequestHeaders();
        const thumbprint: RequestThumbprint = {
            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,
        };
 
        const reqTimestamp = TimeUtils.nowSeconds();
        const response = await this.executePostToTokenEndpoint(
            endpoint,
            requestBody,
            headers,
            thumbprint,
            request.correlationId
        );
 
        const responseHandler = new ResponseHandler(
            this.config.authOptions.clientId,
            this.cacheManager,
            this.cryptoUtils,
            this.logger,
            this.performanceClient,
            this.config.serializableCache,
            this.config.persistencePlugin
        );
 
        responseHandler.validateTokenResponse(
            response.body,
            request.correlationId
        );
        const tokenResponse = await responseHandler.handleServerTokenResponse(
            response.body,
            this.authority,
            reqTimestamp,
            request,
            ApiId.acquireTokenByOBO,
            undefined,
            userAssertionHash
        );
 
        return tokenResponse;
    }
 
    /**
     * generate a server request in accepable format
     * @param request - developer provided CommonOnBehalfOfRequest
     */
    private async createTokenRequestBody(
        request: CommonOnBehalfOfRequest
    ): Promise<string> {
        const parameters = new Map<string, string>();
 
        RequestParameterBuilder.addClientId(
            parameters,
            this.config.authOptions.clientId
        );
 
        RequestParameterBuilder.addScopes(parameters, request.scopes);
 
        RequestParameterBuilder.addGrantType(
            parameters,
            Constants.GrantType.JWT_BEARER
        );
 
        RequestParameterBuilder.addClientInfo(parameters);
 
        RequestParameterBuilder.addLibraryInfo(
            parameters,
            this.config.libraryInfo
        );
        RequestParameterBuilder.addApplicationTelemetry(
            parameters,
            this.config.telemetry.application
        );
        RequestParameterBuilder.addThrottling(parameters);
 
        if (this.serverTelemetryManager) {
            RequestParameterBuilder.addServerTelemetry(
                parameters,
                this.serverTelemetryManager
            );
        }
 
        const correlationId =
            request.correlationId ||
            this.config.cryptoInterface.createNewGuid();
        RequestParameterBuilder.addCorrelationId(parameters, correlationId);
 
        RequestParameterBuilder.addRequestTokenUse(
            parameters,
            AADServerParamKeys.ON_BEHALF_OF
        );
 
        RequestParameterBuilder.addOboAssertion(
            parameters,
            request.oboAssertion
        );
 
        if (this.config.clientCredentials.clientSecret) {
            RequestParameterBuilder.addClientSecret(
                parameters,
                this.config.clientCredentials.clientSecret
            );
        }
 
        const clientAssertion: ClientAssertion | undefined =
            this.config.clientCredentials.clientAssertion;
 
        if (clientAssertion) {
            RequestParameterBuilder.addClientAssertion(
                parameters,
                await getClientAssertion(
                    clientAssertion.assertion,
                    this.config.authOptions.clientId,
                    request.resourceRequestUri
                )
            );
            RequestParameterBuilder.addClientAssertionType(
                parameters,
                clientAssertion.assertionType
            );
        }
 
        if (
            request.claims ||
            (this.config.authOptions.clientCapabilities &&
                this.config.authOptions.clientCapabilities.length > 0)
        ) {
            RequestParameterBuilder.addClaims(
                parameters,
                request.claims,
                this.config.authOptions.clientCapabilities
            );
        }
 
        return UrlUtils.mapToQueryString(parameters);
    }
}