如何为PgBouncer的auth_user配置非明文密码(已启用SCRAM)
PgBouncer auth_user配置SCRAM加密密码失败,服务器已启用SCRAM认证
问题背景
已通过auth_query实现PgBouncer的认证功能,现在想给auth_user配置加密密码。尝试用SCRAM哈希时连接失败,已知MD5加密可行,但后端PostgreSQL服务器已启用SCRAM认证。
当前配置
PgBouncer配置文件
; ; pgbouncer configuration example ; [databases] test5432 = port=5432 host=localhost auth_user=myauthuser alin = port=5435 host=localhost auth_user=myauthuser5435 [pgbouncer] listen_addr = * listen_port = 6432 admin_users = postgres ;stats_users = monitoring userid auth_type = scram-sha-256 ; put these files somewhere sensible: auth_query = SELECT usename, passwd FROM user_search($1) auth_file = users.txt logfile = pgbouncer.log pidfile = pgbouncer.pid server_reset_query = DISCARD ALL; ; default values pool_mode = session default_pool_size = 20 log_pooler_errors = 1
users.txt内容
"postgres" "SCRAM-SHA-256$4096:Ou4b7GtxwKdQ2NnKwHUxoQ==$RT+nGDekJIzK4L9wxGY4W7$ "myauthuser" "asdf" "myauhuser5345" "asdf"
测试命令
psql -h 192.168.1.59 -p 6432 -U alinka test5432
解决方案
核心问题分析
- 密码格式不匹配:当前
auth_type设为scram-sha-256,但auth_file中myauthuser的密码是明文,不符合SCRAM认证要求;同时postgres的SCRAM哈希字符串不完整(SCRAM格式应为SCRAM-SHA-256$迭代次数:盐$客户端密钥哈希$服务器密钥哈希,末尾缺失最后一段)。 - auth_user的认证逻辑:
auth_user是PgBouncer连接后端执行auth_query的专用用户,其密码必须在auth_file中以与auth_type匹配的格式存储,且需与后端PostgreSQL中该用户的密码哈希一致。
具体修复步骤
生成完整的SCRAM哈希
在后端PostgreSQL服务器上执行以下SQL,生成myauthuser和myauthuser5435的合法SCRAM哈希:-- 若用户不存在则创建,存在则更新密码 CREATE USER IF NOT EXISTS myauthuser WITH PASSWORD 'asdf'; CREATE USER IF NOT EXISTS myauthuser5435 WITH PASSWORD 'asdf'; -- 查询用户的完整SCRAM哈希 SELECT usename, passwd FROM pg_shadow WHERE usename IN ('myauthuser', 'myauthuser5435');复制查询结果中的完整哈希字符串(确保包含四个分段)。
修正users.txt文件
将auth_file中的明文密码替换为生成的完整SCRAM哈希,同时补全postgres用户的哈希(若需保留该用户的管理员权限):"postgres" "SCRAM-SHA-256$4096:Ou4b7GtxwKdQ2NnKwHUxoQ==$RT+nGDekJIzK4L9wxGY4W7$完整的服务器密钥哈希段" "myauthuser" "SCRAM-SHA-256$4096:xxxxxx$yyyyyy$zzzzzz" "myauthuser5435" "SCRAM-SHA-256$4096:aaaaaa$bbbbbb$cccccc"注意:每个条目需确保引号完整,哈希字符串无截断。
验证auth_query逻辑
确保user_search函数能正确返回连接用户的用户名和对应的SCRAM哈希(后端PostgreSQL的password_encryption已设为scram-sha-256,因此返回的passwd必须是SCRAM格式)。重启PgBouncer并测试
执行重载命令使配置生效:pgbouncer -R /path/to/your/pgbouncer.ini重新运行测试命令验证连接:
psql -h 192.168.1.59 -p 6432 -U alinka test5432
额外注意事项
- 当
auth_type设为scram-sha-256时,auth_file中所有用户的密码必须是完整的SCRAM哈希,禁止混用明文或MD5格式。 auth_user在后端PostgreSQL中的密码哈希必须与auth_file中的完全一致,否则PgBouncer无法连接后端执行认证查询。
内容的提问来源于stack exchange,提问作者gluetornado
相关产品推荐
相关产品推荐

