Skip to main content

Example: Key Pair Authentication

Documentation

Prerequisites

  • You must have a user configured with key pair authentication, as described in the Snowflake documentation.
  • You must have access to the private key file for the user.

Steps

  1. Load the private key file.
  2. Create a connection using the Snowflake SDK createConnection method.
    • Set the authenticator property to SNOWFLAKE_JWT.
    • Don’t call connect yet.
  3. After creating the connection, pass it to the Promise Helper library’s promisifyConnection function.
  4. On the promisified connection object, await the connect method to establish a connection to Snowflake.

Example Code: Key-Pair Authentication

import { strict as assert } from "node:assert";
import * as crypto from "node:crypto";
import * as fs from "node:fs/promises";
import { promisifyConnection } from "snowflake-promise";
import snowflake from "snowflake-sdk";


// Read the private key file and extract it as a PEM-encoded string.
// For this example, we’ll use a file path to the private key file.
// In production, use a secure storage service such as AWS Secrets
// Manager or Azure Key Vault.
const privateKeyFile = await fs.readFile("/path/to/the/file/rsa_key.p8");
const privateKeyObject = crypto.createPrivateKey({ key: privateKeyFile, format: "pem" });
const privateKey = privateKeyObject.export({ format: "pem", type: "pkcs8" });

// Create a Connection using the SDK’s `createConnection` and promisify it
const connection = promisifyConnection(
snowflake.createConnection({
account: account,
username: username,
authenticator: "SNOWFLAKE_JWT",
privateKey: privateKey.toString(),
}),
);

// Connect to Snowflake
try {
await connection.connect();
console.log("Successfully connected to Snowflake.");
} catch (err) {
assert(err instanceof Error);
console.error("Unable to connect: " + err.message);
}