Skip to content

Instantly share code, notes, and snippets.

@mattgillard
Last active January 31, 2023 06:52
Show Gist options
  • Save mattgillard/f63debb281c9eb26488ea788a5893090 to your computer and use it in GitHub Desktop.
Save mattgillard/f63debb281c9eb26488ea788a5893090 to your computer and use it in GitHub Desktop.
dotnet code to test AWS RDS Proxy IAM authentication with SQL Server
using Microsoft.Data.SqlClient;
using Amazon.RDS;
/*
This code is a sample for generating an RDS auth token to use for IAM authentication with MS SQL server.
ref: https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-proxy-setup.html
Below steps assumes you stored DB user creds in secrets manager when deploying RDS.
1. Create an RDS MS SQL Server (Express is fine for cheapness)
2. Create an RDS Proxy (plug in your requirements)
aws rds create-db-proxy \
--db-proxy-name sqlproxy \
--engine-family SQLSERVER \
--auth Description="MS SQL RDS Proxy",AuthScheme="SECRETS",SecretArn="arn:aws:secretsmanager:ap-southeast-2:1234567890:secret:rdsad5de9b2-a9be-4052-a448-ec5112025942-kyUTPL",IAMAuth="ENABLED",ClientPasswordAuthType="SQL_SERVER_AUTHENTICATION" \
--role-arn "arn:aws:iam::1234567890:role/service-role/rds-proxy-role-1674792657645"\
--vpc-subnet-ids "subnet-xxx" "subnet-yyy" \
--vpc-security-group-ids sg-xxx
3. Register your RDS DB with the proxy:
aws rds register-db-proxy-targets \
--db-proxy-name sqlproxy \
--db-instance-identifiers "sqlexpress"
4. Ensure your IAM User/Role allows rds-db:connect as per https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html
5. Enter resulting Proxy FQDN below in host variable
*/
namespace sqltest
{
class Program
{
static void Main(string[] args)
{
try
{
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
builder.DataSource = "mssql.proxy-cffntbampvu0.ap-southeast-2.rds.amazonaws.com";
builder.InitialCatalog = "master";
var host = "mssql.proxy-cffntbampvu0.ap-southeast-2.rds.amazonaws.com";
var dbName = Environment.GetEnvironmentVariable("DB_NAME");
var user = "admin";
Console.WriteLine($"Generating auth token {host}::{dbName}::{user}");
var authToken =
Amazon.RDS.Util.RDSAuthTokenGenerator.GenerateAuthToken(
host, 1433, user);
using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
{
Console.WriteLine("\nQuery data example:");
Console.WriteLine("=========================================\n");
connection.AccessToken = authToken;
connection.Open();
String sql = "SELECT @@version;";
using (SqlCommand command = new SqlCommand(sql, connection))
{
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0}", reader.GetString(0));
}
}
}
}
}
catch (SqlException e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nDone. Press enter.");
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment