App Service Issue getting access token to azure sql db

Alex Thompson 20 Reputation points
2025-05-27T21:31:34.61+00:00

I have a linux app service hosting a node v20 api that calls and gets an access token through entra for an azure sql db. The access token is fine on first load or after restarting the app, but then in about 1 hour to 1 hour 30 min the token expires and it doesn't go fetch a new one. I am pretty sure my logic is right but I don't know if I'm missing a setting in the app service or my logic isn't right. Here is my code I'm using to get the token. const mssql = require('mssql');

const msal = require('@azure/msal-node');

const crypto = require('crypto');

// Azure AD App Registration details

const tenantID = '';

const clientID = '';

const clientSecret = '';

const authority = https://login.microsoftonline.com/${tenantID};

const sqlServer = '';

const database = '';

Const mySecret =

// MSAL Confidential Client

const cca = new msal.ConfidentialClientApplication({

auth: {

clientId: clientID,

clientSecret: clientSecret,

authority: authority,

},

});

// Token caching

let cachedToken = null;

let tokenExpiresAt = 0;

// SQL connection pooling

let connectionPool = null;

async function getAccessToken() {

const now = Date.now();

if (!cachedToken || now >= tokenExpiresAt - 5 * 60 * 1000) {

console.log('🔄 Fetching new Azure AD access token...');

const result = await cca.acquireTokenByClientCredential({

scopes: ['https://database.windows.net/.default'],

});

if (!result?.accessToken) throw new Error('Failed to acquire access token');

cachedToken = result.accessToken;

tokenExpiresAt = result.expiresOn.getTime();

console.log('✅ Token valid until:', new Date(tokenExpiresAt).toISOString());

}

return cachedToken;

}

async function getConnection() {

const token = await getAccessToken();

if (!connectionPool || !connectionPool.connected) {

connectionPool = await mssql.connect({

server: sqlServer,

database: database,

authentication: {

type: 'azure-active-directory-access-token',

options: { token },

},

options: {

encrypt: true,

trustServerCertificate: false,

},

});

}

return connectionPool;

}

Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
8,930 questions
{count} votes

Accepted answer
  1. Alekhya Vaddepally 1,670 Reputation points Microsoft External Staff Moderator
    2025-05-28T20:21:11.9566667+00:00

    HiAlex Thompson
    To guarantee a clean handshake using new tokens, we recommend rebuilding a fully underlying MSSQL connection pool example, not just calling. close(). This means removing and reinstalling all cashed states:

    async function getConnection() {
      const token = await getAccessToken();
      const shouldRefreshConnection =
        !connectionPool ||
        !connectionPool.connected ||
        Date.now() >= tokenExpiresAt - 5 * 60 * 1000;
      if (shouldRefreshConnection) {
        if (connectionPool) {
          try {
            await connectionPool.close();
          } catch (err) {
            console.warn('Error closing connection pool:', err.message);
          }
          connectionPool = null; // Force reinitialization
        }
        connectionPool = await mssql.connect({
          server: sqlServer,
          database: database,
          authentication: {
            type: 'azure-active-directory-access-token',
            options: { token },
          },
          options: {
            encrypt: true,
            trustServerCertificate: false,
            connectionTimeout: 15000,
          },
        });
      }
      return connectionPool;
    }
    
    

    If this answer was helpful and pointed you in the right direction, please consider clicking "Accept Answer"—it may benefit other community members reading this thread. If you have any further questions, feel free to let us know.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.