我们为此功能实现了一个包并发布到 PyPi。你可以在这里查看https://github.com/labd/django-iam-dbauth https://github.com/labd/django-iam-dbauth
但原则上步骤如下:
First 启用 IAM 身份验证 https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.Enabling.html.
Then 添加策略并将其附加 https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html连接到数据库的角色或用户。
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"rds-db:connect"
],
"Resource": [
"arn:aws:rds-db:us-east-2:1234567890:dbuser:db-ABCDEFGHIJKL01234/db_userx"
]
}
]
}
然后在您的 AWS postgres 上创建一个用户并授予rds_iam
对其的作用:
CREATE USER db_userx WITH LOGIN;
GRANT rds_iam TO db_userx;
对于 Django,您需要一个自定义后端来允许动态生成凭证。
创建一个包,例如your.package.postgresql
with a base.py
in it
import boto3
from django.db.backends.postgresql import base
class DatabaseWrapper(base.DatabaseWrapper):
def get_connection_params(self):
params = super().get_connection_params()
rds_client = boto3.client("rds")
params["password"] = rds_client.generate_db_auth_token(
DBHostname=params.get("host", "localhost"),
Port=params.get("port", 5432),
DBUsername=params.get("user") or getpass.getuser(),
)
return params
然后使用如下设置:
DATABASES = {
"default": {
"HOST": "<hostname>",
"USER": "<user>",
"PORT": 5432,
"ENGINE": "your.package.postgresql"
}
}