Fix MSAL token expiry and silent refresh behavior [Experimental]#22103
Open
aasimkhan30 wants to merge 2 commits into
Open
Fix MSAL token expiry and silent refresh behavior [Experimental]#22103aasimkhan30 wants to merge 2 commits into
aasimkhan30 wants to merge 2 commits into
Conversation
Contributor
There was a problem hiding this comment.
Pull request overview
This PR adjusts the MSSQL extension’s MSAL authentication behavior to reduce repeated interactive prompts and make token lifetime decisions more accurate, addressing reported Entra/MFA login loops and token-expiry-related failures.
Changes:
- Use
AuthenticationResult.expiresOn(access token lifetime) forexpiresOninstead of ID tokenexpclaims. - Refine silent token acquisition: avoid unconditional
forceRefresh, add tenant-aware account selection, and avoid automatically triggering interactive auth from silent flows. - Update MSAL dependencies and add unit tests around tenant selection, force-refresh fallback, silent failures, and expiry mapping.
Reviewed changes
Copilot reviewed 6 out of 7 changed files in this pull request and generated 4 comments.
Show a summary per file
| File | Description |
|---|---|
| extensions/mssql/src/azure/msal/msalAzureAuth.ts | Adjusts silent token acquisition behavior, tenant-specific account lookup, and maps token expiry from expiresOn. |
| extensions/mssql/src/azure/msal/msalAzureController.ts | Uses the new expiry mapping helper and tightens cache-check behavior. |
| extensions/mssql/src/azure/msal/msalAzureCodeGrant.ts | Extends login flow to accept optional prompt/login hints/account for recovery scenarios. |
| extensions/mssql/src/azure/msal/msalAzureDeviceCode.ts | Updates login signature to match base class options interface. |
| extensions/mssql/test/unit/msalAzureController.test.ts | Adds unit coverage for tenant-aware MSAL account selection, force-refresh fallback, silent failure behavior, and expiry mapping. |
| extensions/mssql/package.json | Bumps direct MSAL dependencies to newer major versions. |
| extensions/mssql/package-lock.json | Updates lockfile to reflect MSAL dependency changes and resolved dependency graph. |
Files not reviewed (1)
- extensions/mssql/package-lock.json: Language not supported
Comments suppressed due to low confidence (1)
extensions/mssql/test/unit/msalAzureController.test.ts:354
- This test uses calledOnce and firstCall to validate forceRefresh behavior. To reduce brittleness, assert the silent request via calledWithMatch (including forceRefresh: true) without depending on call count or firstCall indexing.
expect(acquireTokenSilent).to.have.been.calledOnce;
const request = acquireTokenSilent.firstCall.args[0] as msalNode.SilentFlowRequest;
expect(request.account).to.equal(homeAccount);
expect(request.forceRefresh).to.equal(true);
});
Comment on lines
+47
to
+48
| export function getTokenExpirationInSeconds(result: AuthenticationResult): number | undefined { | ||
| return result.expiresOn ? Math.floor(result.expiresOn.getTime() / 1000) : undefined; |
Comment on lines
176
to
183
| try { | ||
| accountInfo = await this.getAccountFromMsalCache(account.key.id); | ||
| accountInfo = await this.getAccountFromMsalCache(account.key.id, tenantId); | ||
| } catch (ex) { | ||
| this.logger.error( | ||
| `Error: Could not fetch account from MSAL cache, re-authentication needed: ${getErrorMessage(ex)}`, | ||
| `Error: Could not fetch account from MSAL cache: ${getErrorMessage(ex)}`, | ||
| ); | ||
| // build refresh token request | ||
| const tenant: ITenant = { | ||
| id: tenantId, | ||
| displayName: "", | ||
| }; | ||
| return this.handleInteractionRequired(tenant, settings, false); | ||
| return null; | ||
| } |
Comment on lines
+319
to
+320
| const account = matchingAccounts[0] ?? null; | ||
|
|
Comment on lines
+327
to
+335
| expect(acquireTokenSilent).to.have.been.calledOnce; | ||
| const request = acquireTokenSilent.firstCall.args[0] as msalNode.SilentFlowRequest; | ||
| expect(request.account).to.equal(targetAccount); | ||
| expect(request.forceRefresh).to.be.undefined; | ||
| expect(request.authority).to.equal( | ||
| `${providerSettings.publicAzureProviderSettings.loginEndpoint}${targetTenantId}`, | ||
| ); | ||
| expect(request.scopes).to.deep.equal(["https://database.windows.net/.default"]); | ||
| }); |
PR Changes
|
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #22103 +/- ##
==========================================
+ Coverage 74.83% 74.98% +0.15%
==========================================
Files 394 394
Lines 120403 120506 +103
Branches 7197 7242 +45
==========================================
+ Hits 90102 90360 +258
+ Misses 30301 30146 -155
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Fixes MSAL token acquisition behavior that could lead to repeated interactive auth prompts and incorrect token lifetime decisions.
Changes:
AuthenticationResult.expiresOninstead of ID tokenexpclaims.forceRefresh: trueon every silent request; force refresh is now only used as a fallback when reusing an account from another tenant for first-time guest-tenant acquisition.null, and interaction-required errors are surfaced instead of immediately launching interactive login fromgetToken.refreshAccessTokenwith a single interactive reauth attempt using tenant/account/login hints.AccountInfoby matching both account id and tenant id.prompt: select_accountfor initial sign-in only, while allowing account/login hints for recovery flows.@azure/msal-node@^5.2.1and@azure/msal-common@^16.6.1.expiresOnmapping.Related: #22031, #22046, #22053, #22078, #22097.
Validation performed:
npm run build:extension:typechecknpm run build:extension:emitnpx eslint --quiet --cache src/azure/msal/msalAzureAuth.ts src/azure/msal/msalAzureController.ts test/unit/msalAzureController.test.tsnpx vscode-test --coverage --grep "MsalAzure"(12 passing)Note: full
npm run testwas not run; this PR was validated with the focused MSAL test suite plus typecheck/lint/build.Code Changes Checklist
npm run test)Reviewers: Please read our reviewer guidelines