是的,您遇到的错误正是因为数据库开启了 SCRAM 认证。以下是修改 PostgreSQL 使用 MD5 认证的详细步骤:
🛠️ 修改 PostgreSQL 使用 MD5 认证
步骤1:找到并编辑 pg_hba.conf 文件
# Ubuntu/Debian (通常位置)
sudo nano /etc/postgresql/*/main/pg_hba.conf
# CentOS/RHEL
sudo nano /var/lib/pgsql/data/pg_hba.conf
# macOS (Homebrew)
sudo nano /usr/local/var/postgres/pg_hba.conf
# 或者通过 psql 查找位置
sudo -u postgres psql -c "SHOW hba_file;"
步骤2:修改认证方法
在 pg_hba.conf 中找到类似这样的行:
# 修改前示例:
host all all 127.0.0.1/32 scram-sha-256
host all all ::1/128 scram-sha-256
host all all 0.0.0.0/0 scram-sha-256
# 修改后:
host all all 127.0.0.1/32 md5
host all all ::1/128 md5
host all all 0.0.0.0/0 md5
步骤3:重启 PostgreSQL 服务
# Ubuntu/Debian
sudo systemctl restart postgresql
# CentOS/RHEL 7+
sudo systemctl restart postgresql-14 # 版本号可能不同
# macOS (Homebrew)
brew services restart postgresql
# 或者直接重启
sudo pg_ctl restart -D /path/to/postgres/data/directory
步骤4:验证配置生效
# 重新连接测试(现在应该能正常工作了)
psql -h your_host -U your_user -d your_db
# 或者在服务器上检查当前认证方法
sudo -u postgres psql -c "SELECT * FROM pg_hba_file_rules;"
🔧 完整的 pg_hba.conf 配置示例
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all md5
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
# Remote connections (根据您的网络调整)
host all all 192.168.1.0/24 md5
host all all 10.0.0.0/8 md5
⚠️ 重要注意事项
- 安全风险:MD5 比 SCRAM-SHA-256 安全性较低
- 密码需要重置:如果用户密码之前是用 SCRAM 加密的,可能需要重置:
ALTER USER your_user PASSWORD 'new_password'; - 生产环境建议:在生产环境中,强烈建议升级客户端而不是降级认证方式
🔄 备选方案:混合配置
如果您只想为特定客户端保留 MD5:
# pg_hba.conf - 混合配置示例
host all old_client 192.168.1.100/32 md5
host all new_client 192.168.1.101/32 scram-sha-256
📋 验证修复结果
修改完成后测试连接:
psql -h localhost -U your_username -d your_database
如果仍有问题,请检查:
- PostgreSQL 日志文件获取详细错误信息
pg_hba.conf语法是否正确(每行字段用tab分隔)- PostgreSQL服务是否成功重启
内容由零声教学AI助手提供,问题来源于学员提问




