Skip to content

Commit bd24fc2

Browse files
KarishmaGhiyaCopilot
authored andcommitted
Add samples for @azure/postgresql-auth
Adds TypeScript and JavaScript samples for both pg and Sequelize usage: - pgConnection: Using getEntraTokenPassword with pg Pool - sequelizeConnection: Using configureEntraIdAuth with Sequelize Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 6bd9a23 commit bd24fc2

11 files changed

Lines changed: 408 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Azure PostgreSQL Auth client library samples for JavaScript (Beta)
2+
3+
These sample programs show how to use the JavaScript client libraries for Azure PostgreSQL Entra ID authentication in some common scenarios.
4+
5+
| **File Name** | **Description** |
6+
| --------------------------------------------------- | -------------------------------------------------------------------------------------- |
7+
| [pgConnection.js][pgconnection] | Connect to Azure Database for PostgreSQL using Entra ID auth with the `pg` library |
8+
| [sequelizeConnection.js][sequelizeconnection] | Connect to Azure Database for PostgreSQL using Entra ID auth with Sequelize ORM |
9+
10+
## Prerequisites
11+
12+
The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule).
13+
14+
You need access to an [Azure Database for PostgreSQL Flexible Server](https://learn.microsoft.com/azure/postgresql/flexible-server/overview) configured for [Microsoft Entra ID authentication](https://learn.microsoft.com/azure/postgresql/flexible-server/concepts-azure-ad-authentication).
15+
16+
## Setup
17+
18+
To run the samples using the published version of the package:
19+
20+
1. Install the dependencies using `npm`:
21+
22+
```bash
23+
npm install
24+
```
25+
26+
2. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically.
27+
28+
3. Run whichever samples you like (note that some samples may require additional setup, see the table above):
29+
30+
```bash
31+
node pgConnection.js
32+
```
33+
34+
## Next Steps
35+
36+
Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients.
37+
38+
[pgconnection]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/postgresql/postgresql-auth/samples/v1-beta/javascript/pgConnection.js
39+
[sequelizeconnection]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/postgresql/postgresql-auth/samples/v1-beta/javascript/sequelizeConnection.js
40+
[apiref]: https://learn.microsoft.com/javascript/api/@azure/postgresql-auth
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"name": "@azure-samples/postgresql-auth-js-beta",
3+
"private": true,
4+
"version": "1.0.0",
5+
"description": "Azure PostgreSQL Entra ID authentication client library samples for JavaScript (Beta)",
6+
"engines": {
7+
"node": ">=20.0.0"
8+
},
9+
"repository": {
10+
"type": "git",
11+
"url": "git+https://github.com/Azure/azure-sdk-for-js.git",
12+
"directory": "sdk/postgresql/postgresql-auth"
13+
},
14+
"dependencies": {
15+
"@azure/postgresql-auth": "next",
16+
"@azure/identity": "^4.0.1",
17+
"dotenv": "latest",
18+
"pg": "^8.0.0",
19+
"sequelize": "^6.0.0"
20+
}
21+
}
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
/**
5+
* @summary Demonstrates how to connect to Azure Database for PostgreSQL using
6+
* Entra ID authentication with the `pg` (node-postgres) library.
7+
*/
8+
9+
const pg = require("pg");
10+
const { DefaultAzureCredential } = require("@azure/identity");
11+
const { getEntraTokenPassword } = require("@azure/postgresql-auth");
12+
const dotenv = require("dotenv");
13+
14+
dotenv.config();
15+
16+
const { Pool } = pg;
17+
18+
async function main() {
19+
const credential = new DefaultAzureCredential();
20+
21+
// Create a connection pool that uses Entra ID tokens as the password.
22+
// The `password` option accepts a function that returns a Promise<string>,
23+
// so the token is refreshed automatically on each new connection.
24+
const pool = new Pool({
25+
host: process.env.PGHOST,
26+
port: Number(process.env.PGPORT || 5432),
27+
database: process.env.PGDATABASE,
28+
user: process.env.PGUSER,
29+
password: () => getEntraTokenPassword(credential),
30+
ssl: { rejectUnauthorized: true },
31+
connectionTimeoutMillis: 20000,
32+
idleTimeoutMillis: 30000,
33+
});
34+
35+
try {
36+
console.log("Connecting to Azure Database for PostgreSQL...");
37+
38+
const client = await pool.connect();
39+
try {
40+
const { rows } = await client.query(
41+
"SELECT current_user, now() AS server_time, pg_backend_pid() AS backend_pid",
42+
);
43+
console.log("Connected successfully:", rows[0]);
44+
} finally {
45+
client.release();
46+
}
47+
} finally {
48+
await pool.end();
49+
console.log("Pool closed.");
50+
}
51+
}
52+
53+
main().catch((error) => {
54+
console.error("Error:", error.message);
55+
process.exit(1);
56+
});
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Azure Database for PostgreSQL Configuration
2+
# Copy this file to .env and update with your server details
3+
4+
# PostgreSQL server hostname (Azure Database for PostgreSQL)
5+
PGHOST=your-server.postgres.database.azure.com
6+
7+
# PostgreSQL server port (default is 5432)
8+
PGPORT=5432
9+
10+
# Database name
11+
PGDATABASE=postgres
12+
13+
# Username (your Azure Entra ID user principal name)
14+
PGUSER=your-user@your-domain.onmicrosoft.com
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
/**
5+
* @summary Demonstrates how to connect to Azure Database for PostgreSQL using
6+
* Entra ID authentication with Sequelize ORM.
7+
*/
8+
9+
const { Sequelize } = require("sequelize");
10+
const { DefaultAzureCredential } = require("@azure/identity");
11+
const { configureEntraIdAuth } = require("@azure/postgresql-auth");
12+
const dotenv = require("dotenv");
13+
14+
dotenv.config();
15+
16+
async function main() {
17+
const credential = new DefaultAzureCredential();
18+
19+
// Create a Sequelize instance with PostgreSQL dialect
20+
const sequelize = new Sequelize({
21+
dialect: "postgres",
22+
host: process.env.PGHOST,
23+
port: Number(process.env.PGPORT || 5432),
24+
database: process.env.PGDATABASE,
25+
dialectOptions: { ssl: { rejectUnauthorized: true } },
26+
pool: { min: 2, max: 10, idle: 30000 },
27+
});
28+
29+
// Register the Entra ID `beforeConnect` hook.
30+
// This automatically sets the username and password on each new connection.
31+
configureEntraIdAuth(sequelize, credential);
32+
33+
try {
34+
console.log("Connecting to Azure Database for PostgreSQL via Sequelize...");
35+
36+
await sequelize.authenticate();
37+
console.log("Connected successfully with Entra ID!");
38+
39+
const [results] = await sequelize.query(
40+
"SELECT current_user, now() AS server_time, pg_backend_pid() AS backend_pid",
41+
);
42+
console.log("Query result:", results[0]);
43+
} finally {
44+
await sequelize.close();
45+
console.log("Connections closed.");
46+
}
47+
}
48+
49+
main().catch((error) => {
50+
console.error("Error:", error.message);
51+
process.exit(1);
52+
});
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Azure PostgreSQL Auth client library samples for TypeScript (Beta)
2+
3+
These sample programs show how to use the TypeScript client libraries for Azure PostgreSQL Entra ID authentication in some common scenarios.
4+
5+
| **File Name** | **Description** |
6+
| --------------------------------------------------- | -------------------------------------------------------------------------------------- |
7+
| [pgConnection.ts][pgconnection] | Connect to Azure Database for PostgreSQL using Entra ID auth with the `pg` library |
8+
| [sequelizeConnection.ts][sequelizeconnection] | Connect to Azure Database for PostgreSQL using Entra ID auth with Sequelize ORM |
9+
10+
## Prerequisites
11+
12+
The sample programs are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule).
13+
14+
Before running the samples in this directory, you need to install the TypeScript compiler:
15+
16+
```bash
17+
npm install -g typescript
18+
```
19+
20+
You need access to an [Azure Database for PostgreSQL Flexible Server](https://learn.microsoft.com/azure/postgresql/flexible-server/overview) configured for [Microsoft Entra ID authentication](https://learn.microsoft.com/azure/postgresql/flexible-server/concepts-azure-ad-authentication).
21+
22+
## Setup
23+
24+
To run the samples using the published version of the package:
25+
26+
1. Install the dependencies using `npm`:
27+
28+
```bash
29+
npm install
30+
```
31+
32+
2. Compile the samples:
33+
34+
```bash
35+
npm run build
36+
```
37+
38+
3. Edit the file `sample.env`, adding the correct credentials to access the Azure service and run the samples. Then rename the file from `sample.env` to just `.env`. The sample programs will read this file automatically.
39+
40+
4. Run whichever samples you like (note that some samples may require additional setup, see the table above):
41+
42+
```bash
43+
node dist/pgConnection.js
44+
```
45+
46+
Alternatively, run a sample using `ts-node`:
47+
48+
```bash
49+
npx ts-node src/pgConnection.ts
50+
```
51+
52+
## Next Steps
53+
54+
Take a look at our [API Documentation][apiref] for more information about the APIs that are available in the clients.
55+
56+
[pgconnection]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/postgresql/postgresql-auth/samples/v1-beta/typescript/src/pgConnection.ts
57+
[sequelizeconnection]: https://github.com/Azure/azure-sdk-for-js/blob/main/sdk/postgresql/postgresql-auth/samples/v1-beta/typescript/src/sequelizeConnection.ts
58+
[apiref]: https://learn.microsoft.com/javascript/api/@azure/postgresql-auth
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
{
2+
"name": "@azure-samples/postgresql-auth-ts-beta",
3+
"private": true,
4+
"version": "1.0.0",
5+
"description": "Azure PostgreSQL Entra ID authentication client library samples for TypeScript (Beta)",
6+
"engines": {
7+
"node": ">=20.0.0"
8+
},
9+
"scripts": {
10+
"build": "tsc",
11+
"prebuild": "rimraf dist/"
12+
},
13+
"repository": {
14+
"type": "git",
15+
"url": "git+https://github.com/Azure/azure-sdk-for-js.git",
16+
"directory": "sdk/postgresql/postgresql-auth"
17+
},
18+
"dependencies": {
19+
"@azure/postgresql-auth": "next",
20+
"@azure/identity": "^4.0.1",
21+
"dotenv": "latest",
22+
"pg": "^8.0.0",
23+
"sequelize": "^6.0.0"
24+
},
25+
"devDependencies": {
26+
"@types/node": "^20.0.0",
27+
"@types/pg": "^8.0.0",
28+
"typescript": "~5.8.2",
29+
"rimraf": "latest"
30+
}
31+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Azure Database for PostgreSQL Configuration
2+
# Copy this file to .env and update with your server details
3+
4+
# PostgreSQL server hostname (Azure Database for PostgreSQL)
5+
PGHOST=your-server.postgres.database.azure.com
6+
7+
# PostgreSQL server port (default is 5432)
8+
PGPORT=5432
9+
10+
# Database name
11+
PGDATABASE=postgres
12+
13+
# Username (your Azure Entra ID user principal name)
14+
PGUSER=your-user@your-domain.onmicrosoft.com
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
// Copyright (c) Microsoft Corporation.
2+
// Licensed under the MIT License.
3+
4+
/**
5+
* @summary Demonstrates how to connect to Azure Database for PostgreSQL using
6+
* Entra ID authentication with the `pg` (node-postgres) library.
7+
*/
8+
9+
import pg from "pg";
10+
import { DefaultAzureCredential } from "@azure/identity";
11+
import { getEntraTokenPassword } from "@azure/postgresql-auth";
12+
import dotenv from "dotenv";
13+
14+
dotenv.config();
15+
16+
const { Pool } = pg;
17+
18+
async function main(): Promise<void> {
19+
const credential = new DefaultAzureCredential();
20+
21+
// Create a connection pool that uses Entra ID tokens as the password.
22+
// The `password` option accepts a function that returns a Promise<string>,
23+
// so the token is refreshed automatically on each new connection.
24+
const pool = new Pool({
25+
host: process.env.PGHOST,
26+
port: Number(process.env.PGPORT || 5432),
27+
database: process.env.PGDATABASE,
28+
user: process.env.PGUSER,
29+
password: () => getEntraTokenPassword(credential),
30+
ssl: { rejectUnauthorized: true },
31+
connectionTimeoutMillis: 20000,
32+
idleTimeoutMillis: 30000,
33+
});
34+
35+
try {
36+
console.log("Connecting to Azure Database for PostgreSQL...");
37+
38+
const client = await pool.connect();
39+
try {
40+
const { rows } = await client.query(
41+
"SELECT current_user, now() AS server_time, pg_backend_pid() AS backend_pid",
42+
);
43+
console.log("Connected successfully:", rows[0]);
44+
} finally {
45+
client.release();
46+
}
47+
} finally {
48+
await pool.end();
49+
console.log("Pool closed.");
50+
}
51+
}
52+
53+
main().catch((error) => {
54+
console.error("Error:", error.message);
55+
process.exit(1);
56+
});

0 commit comments

Comments
 (0)