We are builing a nestjs application that connects to Azure Postgresql Flexible Database server using Typeorm. We are following the passwordless apparoach using managed identity and using Entra token. Our application is able to connect to Database but after the token expires( in our case 24 hours) our application goes down as DB connection is not getting refreshed automatically.
has anyone else faced this issue?
We tried to refresh the token after 23 hours using the https://learn.microsoft.com/en-us/javascript/api/overview/azure/identity-readme?view=azure-node-latest , but we could see that a new token was not getting generated even after 24 hours.
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { ManagedIdentityCredential } from '@azure/identity';
@Module({
imports: [
TypeOrmModule.forRootAsync({
useFactory: async () => {
const credential = new ManagedIdentityCredential(); // Use ManagedIdentityCredential
// Fetch the access token
const tokenResponse = await credential.getToken('https://ossrdbms-aad.database.windows.net/.default');
return {
type: 'postgres',
host: '<YOUR_DATABASE_SERVER_NAME>.postgres.database.azure.com', // Replace with your server name
port: 5432,
username: '<YOUR_AAD_USER>@<YOUR_DATABASE_SERVER_NAME>', // Replace with your Azure AD user
password: tokenResponse.token, // Use the fetched access token as the password
database: '<YOUR_DATABASE_NAME>', // Replace with your database name
ssl: { rejectUnauthorized: false }, // Adjust based on your SSL requirements
entities: [/* Your entities here */],
synchronize: true, // Set to false in production
};
},
}),
],
})
export class DatabaseModule {}
import { Module } from '@nestjs/common';
import { DatabaseModule } from './database/database.module'; // Adjust the path as necessary
@Module({
imports: [
DatabaseModule, // Import the DatabaseModule here
// Other modules can be added here as needed
],
controllers: [],
providers: [],
})
export class AppModule {}