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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
/*
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License.
 */
 
import {
    ICrypto,
    Logger,
    Constants,
    AuthorizationCodeClient,
    AuthError,
    IPerformanceClient,
    PerformanceEvents,
    invokeAsync,
    invoke,
    ProtocolMode,
    CommonAuthorizationUrlRequest,
    AuthorizeProtocol,
    PkceCodes,
} from "@azure/msal-common/browser";
import {
    initializeAuthorizationRequest,
    StandardInteractionClient,
} from "./StandardInteractionClient.js";
import * as BrowserPerformanceEvents from "../telemetry/BrowserPerformanceEvents.js";
import { BrowserConfiguration } from "../config/Configuration.js";
import { BrowserCacheManager } from "../cache/BrowserCacheManager.js";
import { EventHandler } from "../event/EventHandler.js";
import { INavigationClient } from "../navigation/INavigationClient.js";
import {
    createBrowserAuthError,
    BrowserAuthErrorCodes,
} from "../error/BrowserAuthError.js";
import {
    InteractionType,
    ApiId,
    BrowserConstants,
} from "../utils/BrowserConstants.js";
import {
    initiateCodeRequest,
    initiateCodeFlowWithPost,
    initiateEarRequest,
    removeHiddenIframe,
} from "../interaction_handler/SilentHandler.js";
import { SsoSilentRequest } from "../request/SsoSilentRequest.js";
import { AuthenticationResult } from "../response/AuthenticationResult.js";
import * as BrowserUtils from "../utils/BrowserUtils.js";
import * as ResponseHandler from "../response/ResponseHandler.js";
import * as Authorize from "../protocol/Authorize.js";
import { generatePkceCodes } from "../crypto/PkceGenerator.js";
import { isPlatformAuthAllowed } from "../broker/nativeBroker/PlatformAuthProvider.js";
import { generateEarKey } from "../crypto/BrowserCrypto.js";
import { IPlatformAuthHandler } from "../broker/nativeBroker/IPlatformAuthHandler.js";
import {
    getDiscoveredAuthority,
    initializeServerTelemetryManager,
} from "./BaseInteractionClient.js";
 
export class SilentIframeClient extends StandardInteractionClient {
    protected apiId: ApiId;
    protected nativeStorage: BrowserCacheManager;
 
    constructor(
        config: BrowserConfiguration,
        storageImpl: BrowserCacheManager,
        browserCrypto: ICrypto,
        logger: Logger,
        eventHandler: EventHandler,
        navigationClient: INavigationClient,
        apiId: ApiId,
        performanceClient: IPerformanceClient,
        nativeStorageImpl: BrowserCacheManager,
        correlationId: string,
        platformAuthProvider?: IPlatformAuthHandler
    ) {
        super(
            config,
            storageImpl,
            browserCrypto,
            logger,
            eventHandler,
            navigationClient,
            performanceClient,
            correlationId,
            platformAuthProvider
        );
        this.apiId = apiId;
        this.nativeStorage = nativeStorageImpl;
    }
 
    /**
     * Acquires a token silently by opening a hidden iframe to the /authorize endpoint with prompt=none or prompt=no_session
     * @param request
     */
    async acquireToken(
        request: SsoSilentRequest
    ): Promise<AuthenticationResult> {
        // Check that we have some SSO data
        if (
            !request.loginHint &&
            !request.sid &&
            (!request.account || !request.account.username)
        ) {
            this.logger.warning(
                "No user hint provided. The authorization server may need more information to complete this request.",
                this.correlationId
            );
        }
 
        // Check the prompt value
        const inputRequest = { ...request };
        if (inputRequest.prompt) {
            if (
                inputRequest.prompt !== Constants.PromptValue.NONE &&
                inputRequest.prompt !== Constants.PromptValue.NO_SESSION
            ) {
                this.logger.warning(
                    `SilentIframeClient. Replacing invalid prompt '${inputRequest.prompt}' with '${Constants.PromptValue.NONE}'`,
                    this.correlationId
                );
                inputRequest.prompt = Constants.PromptValue.NONE;
            }
        } else {
            inputRequest.prompt = Constants.PromptValue.NONE;
        }
 
        // Create silent request
        const silentRequest: CommonAuthorizationUrlRequest = await invokeAsync(
            initializeAuthorizationRequest,
            BrowserPerformanceEvents.StandardInteractionClientInitializeAuthorizationRequest,
            this.logger,
            this.performanceClient,
            this.correlationId
        )(
            inputRequest,
            InteractionType.Silent,
            this.config,
            this.browserCrypto,
            this.browserStorage,
            this.logger,
            this.performanceClient,
            this.correlationId
        );
        silentRequest.platformBroker = isPlatformAuthAllowed(
            this.config,
            this.logger,
            this.correlationId,
            this.platformAuthProvider,
            silentRequest.authenticationScheme
        );
        BrowserUtils.preconnect(silentRequest.authority);
 
        if (this.config.system.protocolMode === ProtocolMode.EAR) {
            return this.executeEarFlow(silentRequest);
        } else {
            return this.executeCodeFlow(silentRequest);
        }
    }
 
    /**
     * Executes auth code + PKCE flow
     * @param request
     * @returns
     */
    async executeCodeFlow(
        request: CommonAuthorizationUrlRequest
    ): Promise<AuthenticationResult> {
        let authClient: AuthorizationCodeClient | undefined;
        const serverTelemetryManager = initializeServerTelemetryManager(
            this.apiId,
            this.config.auth.clientId,
            this.correlationId,
            this.browserStorage,
            this.logger
        );
 
        try {
            // Initialize the client
            authClient = await invokeAsync(
                this.createAuthCodeClient.bind(this),
                BrowserPerformanceEvents.StandardInteractionClientCreateAuthCodeClient,
                this.logger,
                this.performanceClient,
                request.correlationId
            )({
                serverTelemetryManager,
                requestAuthority: request.authority,
                requestAzureCloudOptions: request.azureCloudOptions,
                requestExtraQueryParameters: request.extraQueryParameters,
                account: request.account,
            });
 
            return await invokeAsync(
                this.silentTokenHelper.bind(this),
                BrowserPerformanceEvents.SilentIframeClientTokenHelper,
                this.logger,
                this.performanceClient,
                request.correlationId
            )(authClient, request);
        } catch (e) {
            if (e instanceof AuthError) {
                (e as AuthError).setCorrelationId(this.correlationId);
                serverTelemetryManager.cacheFailedRequest(e);
            }
 
            if (
                !authClient ||
                !(e instanceof AuthError) ||
                e.errorCode !== BrowserConstants.INVALID_GRANT_ERROR
            ) {
                throw e;
            }
 
            this.performanceClient.addFields(
                {
                    retryError: e.errorCode,
                },
                this.correlationId
            );
 
            return await invokeAsync(
                this.silentTokenHelper.bind(this),
                BrowserPerformanceEvents.SilentIframeClientTokenHelper,
                this.logger,
                this.performanceClient,
                this.correlationId
            )(authClient, request);
        }
    }
 
    /**
     * Executes EAR flow
     * @param request
     */
    async executeEarFlow(
        request: CommonAuthorizationUrlRequest
    ): Promise<AuthenticationResult> {
        const {
            correlationId,
            authority,
            azureCloudOptions,
            extraQueryParameters,
            account,
        } = request;
        const discoveredAuthority = await invokeAsync(
            getDiscoveredAuthority,
            BrowserPerformanceEvents.StandardInteractionClientGetDiscoveredAuthority,
            this.logger,
            this.performanceClient,
            correlationId
        )(
            this.config,
            this.correlationId,
            this.performanceClient,
            this.browserStorage,
            this.logger,
            authority,
            azureCloudOptions,
            extraQueryParameters,
            account
        );
 
        const earJwk = await invokeAsync(
            generateEarKey,
            BrowserPerformanceEvents.GenerateEarKey,
            this.logger,
            this.performanceClient,
            correlationId
        )();
        const pkceCodes = await invokeAsync(
            generatePkceCodes,
            BrowserPerformanceEvents.GeneratePkceCodes,
            this.logger,
            this.performanceClient,
            correlationId
        )(this.performanceClient, this.logger, correlationId);
        const silentRequest = {
            ...request,
            earJwk: earJwk,
            codeChallenge: pkceCodes.challenge,
        };
        const iframe = await invokeAsync(
            initiateEarRequest,
            BrowserPerformanceEvents.SilentHandlerInitiateAuthRequest,
            this.logger,
            this.performanceClient,
            correlationId
        )(
            this.config,
            discoveredAuthority,
            silentRequest,
            this.logger,
            this.performanceClient
        );
 
        const responseType = this.config.auth.OIDCOptions.responseMode;
        let responseString: string;
        try {
            responseString = await invokeAsync(
                BrowserUtils.waitForBridgeResponse,
                BrowserPerformanceEvents.SilentHandlerMonitorIframeForHash,
                this.logger,
                this.performanceClient,
                correlationId
            )(
                this.config.system.iframeBridgeTimeout,
                this.logger,
                this.browserCrypto,
                request,
                this.performanceClient,
                this.config.experimental
            );
        } finally {
            invoke(
                removeHiddenIframe,
                BrowserPerformanceEvents.RemoveHiddenIframe,
                this.logger,
                this.performanceClient,
                correlationId
            )(iframe);
        }
 
        const serverParams = invoke(
            ResponseHandler.deserializeResponse,
            BrowserPerformanceEvents.DeserializeResponse,
            this.logger,
            this.performanceClient,
            correlationId
        )(responseString, responseType, this.logger, this.correlationId);
 
        if (!serverParams.ear_jwe && serverParams.code) {
            // If server doesn't support EAR, they may fallback to auth code flow instead
            const authClient = await invokeAsync(
                this.createAuthCodeClient.bind(this),
                BrowserPerformanceEvents.StandardInteractionClientCreateAuthCodeClient,
                this.logger,
                this.performanceClient,
                correlationId
            )({
                serverTelemetryManager: initializeServerTelemetryManager(
                    this.apiId,
                    this.config.auth.clientId,
                    correlationId,
                    this.browserStorage,
                    this.logger
                ),
                requestAuthority: request.authority,
                requestAzureCloudOptions: request.azureCloudOptions,
                requestExtraQueryParameters: request.extraQueryParameters,
                account: request.account,
                authority: discoveredAuthority,
            });
 
            return invokeAsync(
                Authorize.handleResponseCode,
                BrowserPerformanceEvents.HandleResponseCode,
                this.logger,
                this.performanceClient,
                correlationId
            )(
                silentRequest,
                serverParams,
                pkceCodes.verifier,
                this.apiId,
                this.config,
                authClient,
                this.browserStorage,
                this.nativeStorage,
                this.eventHandler,
                this.logger,
                this.performanceClient,
                this.platformAuthProvider
            );
        } else {
            return invokeAsync(
                Authorize.handleResponseEAR,
                BrowserPerformanceEvents.HandleResponseEar,
                this.logger,
                this.performanceClient,
                correlationId
            )(
                silentRequest,
                serverParams,
                this.apiId,
                this.config,
                discoveredAuthority,
                this.browserStorage,
                this.nativeStorage,
                this.eventHandler,
                this.logger,
                this.performanceClient,
                this.platformAuthProvider
            );
        }
    }
 
    /**
     * Verifies SSO capability by making an iframe request to /authorize without exchanging the code for tokens.
     * This is useful for verifying SSO capability in the background without the overhead of a full token exchange.
     * @param request - The SSO silent request
     * @returns true if SSO verification was successful with a valid authorization code, false otherwise
     */
    async verifySso(request: SsoSilentRequest): Promise<boolean> {
        const inputRequest = { ...request };
        if (!inputRequest.prompt) {
            inputRequest.prompt = Constants.PromptValue.NONE;
        }
 
        // Create silent request
        const silentRequest: CommonAuthorizationUrlRequest = await invokeAsync(
            initializeAuthorizationRequest,
            BrowserPerformanceEvents.StandardInteractionClientInitializeAuthorizationRequest,
            this.logger,
            this.performanceClient,
            this.correlationId
        )(
            inputRequest,
            InteractionType.Silent,
            this.config,
            this.browserCrypto,
            this.browserStorage,
            this.logger,
            this.performanceClient,
            this.correlationId
        );
 
        const authClient: AuthorizationCodeClient = await invokeAsync(
            this.createAuthCodeClient.bind(this),
            BrowserPerformanceEvents.StandardInteractionClientCreateAuthCodeClient,
            this.logger,
            this.performanceClient,
            this.correlationId
        )({
            serverTelemetryManager: initializeServerTelemetryManager(
                this.apiId,
                this.config.auth.clientId,
                this.correlationId,
                this.browserStorage,
                this.logger
            ),
            requestAuthority: silentRequest.authority,
            requestAzureCloudOptions: silentRequest.azureCloudOptions,
            requestExtraQueryParameters: silentRequest.extraQueryParameters,
            account: silentRequest.account,
        });
 
        const { serverParams } = await this.silentAuthorizeHelper(
            authClient,
            silentRequest
        );
 
        const correlationId = silentRequest.correlationId;
 
        // Validate the response - this checks for errors and validates state
        AuthorizeProtocol.validateAuthorizationResponse(
            serverParams,
            silentRequest.state
        );
 
        // Verify a valid authorization code is present
        if (!serverParams.code) {
            this.logger.warning(
                "SSO verification response did not contain an authorization code",
                correlationId
            );
            return false;
        }
 
        this.logger.verbose(
            "SSO verification completed successfully with valid authorization code - skipped token exchange",
            correlationId
        );
        return true;
    }
 
    /**
     * Currently Unsupported
     */
    logout(): Promise<void> {
        // Synchronous so we must reject
        return Promise.reject(
            createBrowserAuthError(
                BrowserAuthErrorCodes.silentLogoutUnsupported
            )
        );
    }
 
    /**
     * Helper which acquires an authorization code silently using a hidden iframe from given url
     * using the scopes requested as part of the id, and exchanges the code for a set of OAuth tokens.
     * @param navigateUrl
     * @param userRequestScopes
     */
    protected async silentTokenHelper(
        authClient: AuthorizationCodeClient,
        request: CommonAuthorizationUrlRequest
    ): Promise<AuthenticationResult> {
        const { serverParams, pkceCodes } = await this.silentAuthorizeHelper(
            authClient,
            request
        );
 
        return invokeAsync(
            Authorize.handleResponseCode,
            BrowserPerformanceEvents.HandleResponseCode,
            this.logger,
            this.performanceClient,
            request.correlationId
        )(
            request,
            serverParams,
            pkceCodes.verifier,
            this.apiId,
            this.config,
            authClient,
            this.browserStorage,
            this.nativeStorage,
            this.eventHandler,
            this.logger,
            this.performanceClient,
            this.platformAuthProvider
        );
    }
 
    /**
     * Shared helper that generates PKCE codes, builds the /authorize URL,
     * loads it in a hidden iframe, waits for the redirect-bridge response,
     * and returns the deserialized server parameters along with the PKCE codes
     * and the request that was sent.
     */
    private async silentAuthorizeHelper(
        authClient: AuthorizationCodeClient,
        request: CommonAuthorizationUrlRequest
    ): Promise<{
        serverParams: ReturnType<typeof ResponseHandler.deserializeResponse>;
        pkceCodes: PkceCodes;
        silentRequest: CommonAuthorizationUrlRequest;
    }> {
        const correlationId = request.correlationId;
        const pkceCodes = await invokeAsync(
            generatePkceCodes,
            BrowserPerformanceEvents.GeneratePkceCodes,
            this.logger,
            this.performanceClient,
            correlationId
        )(this.performanceClient, this.logger, correlationId);
 
        const silentRequest = {
            ...request,
            codeChallenge: pkceCodes.challenge,
        };
 
        let iframe: HTMLIFrameElement;
        if (request.httpMethod === Constants.HttpMethod.POST) {
            iframe = await invokeAsync(
                initiateCodeFlowWithPost,
                BrowserPerformanceEvents.SilentHandlerInitiateAuthRequest,
                this.logger,
                this.performanceClient,
                correlationId
            )(
                this.config,
                authClient.authority,
                silentRequest,
                this.logger,
                this.performanceClient
            );
        } else {
            // Create authorize request url
            const navigateUrl = await invokeAsync(
                Authorize.getAuthCodeRequestUrl,
                PerformanceEvents.GetAuthCodeUrl,
                this.logger,
                this.performanceClient,
                correlationId
            )(
                this.config,
                authClient.authority,
                silentRequest,
                this.logger,
                this.performanceClient
            );
 
            // Get the frame handle for the silent request
            iframe = await invokeAsync(
                initiateCodeRequest,
                BrowserPerformanceEvents.SilentHandlerInitiateAuthRequest,
                this.logger,
                this.performanceClient,
                correlationId
            )(navigateUrl, this.performanceClient, this.logger, correlationId);
        }
 
        const responseType = this.config.auth.OIDCOptions.responseMode;
        // Wait for response from the redirect bridge.
        let responseString: string;
        try {
            responseString = await invokeAsync(
                BrowserUtils.waitForBridgeResponse,
                BrowserPerformanceEvents.SilentHandlerMonitorIframeForHash,
                this.logger,
                this.performanceClient,
                correlationId
            )(
                this.config.system.iframeBridgeTimeout,
                this.logger,
                this.browserCrypto,
                request,
                this.performanceClient,
                this.config.experimental
            );
        } finally {
            invoke(
                removeHiddenIframe,
                BrowserPerformanceEvents.RemoveHiddenIframe,
                this.logger,
                this.performanceClient,
                correlationId
            )(iframe);
        }
 
        const serverParams = invoke(
            ResponseHandler.deserializeResponse,
            BrowserPerformanceEvents.DeserializeResponse,
            this.logger,
            this.performanceClient,
            correlationId
        )(responseString, responseType, this.logger, this.correlationId);
 
        return { serverParams, pkceCodes, silentRequest };
    }
}