IAM Authentication with Postgres

Filed under aws on September 15, 2020

Getting IAM auth in Postgres is a pretty easy process. The first thing we’ll need to do is to enable it in our RDS instance

Enable RDS

We also need to create ourselves a user within Postgres and grant it the rds_iam role.

CREATE USER iam_authed_user LOGIN;
GRANT rds_iam TO iam_authed_user;

We’re ready to get ourselves a temporary auth token. In golang, use rdsutils.BuilAuthToken

endpoint := fmt.Sprintf("%s:%d", DatabaseHost, DatabasePort)
tok, err := rdsutils.BuildAuthToken(endpoint,
		region, DatabaseUser, credentials)

Where region is the AWS region and credentials is an AWS credentials provider. Important to note that the endpoint parameter contains both the host and the port. We then use this token to connect to our database

db, err := sqlx.Connect("postgres",
    fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s",
        DatabaseHost, DatabasePort, DatabaseUser, tok, DatabaseName))

The generated token should last 15 minutes, so you’ll have plenty of time to establish a connection.

Further Configuration

The above will work with a developer, but what about when we want to deploy our code out into AWS?

For that we need another IAM policy to grant the appropriate permissions to login with that user. To do this, grant your execution role the rds-db:connect permission.

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "rds-db:connect",
            "Resource": "arn:aws:rds-db:ap-southeast-2:${AWS::AccountId}:dbuser:${DbIdentifier}/${DbUser}"
        }
    ]
}

This will allow your application to call the appropriate routines to get the signed token.


Stephen Gream

Written by Stephen Gream who lives and works in Melbourne, Australia. You should follow him on Minds