Snowflake — key pair authentication
Once you have set up your Snowflake account for key pair authentication, you can use the script below to test this:
Once you have set up your Snowflake account for key pair authentication, you can use the script below to test this:
import snowflake.connector
from cryptography.hazmat.primitives import serialization
# Snowflake connection parameters
account = 'your snowflake account'
user = 'your snowflake user'
private_key_path = 'rsa_key.p8'
private_key_passphrase = 'your passphrase'
warehouse = 'your warehouse'
database = 'your database'
schema = 'your schema'
# Read the private key
with open(private_key_path, 'rb') as key_file:
private_key_data = key_file.read()
# Load the private key with passphrase
private_key = serialization.load_pem_private_key(
private_key_data,
password=private_key_passphrase.encode()
)
# Convert the key to the expected format
pkb = private_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
# Establish a connection to Snowflake
conn = snowflake.connector.connect(
account=account,
user=user,
private_key=pkb,
warehouse=warehouse,
database=database,
schema=schema
)
# Execute a query
cursor = conn.cursor()
cursor.execute("SELECT CURRENT_VERSION()")
row = cursor.fetchone()
print(row)
# Clean up
cursor.close()
conn.close()The result:
(‘9.7.2’,)
Which is the result of SELECT CURRENT_VERSION().
Added to this, with the TYPE setting on the USER level, make sure to set this user to the proper type:
ALTER USER xx SET TYPE = SERVICE;This TYPE = SERVICE is the non-human alternative for TYPE = PERSON. With the upcoming changes in Snowflake authentication, SERVICE or PERSON will eventually be the only options valid.
- PERSON will require MFA
- SERVICE will require key pair authentication
When you forget this last step, Snowflake will default your user to TYPE = PERSON.