# 错误：Authentication failed 排查指南

> 针对 PostgreSQL Authentication failed 错误的完整排查流程，包括密码错误、pg_hba.conf 配置、用户权限等常见原因的解决方案。

---

## Content

# 错误：Authentication failed 排查指南

当使用 MCP postgres 工具连接数据库时，如果遇到 "Authentication failed" 错误，说明身份验证失败。本文提供完整的排查和解决方案。

## 错误现象

```
Error: Authentication failed for user 'username'
Error: password authentication failed for user 'username'
```

## 错误原因

1. 用户名或密码错误
2. pg_hba.conf 配置问题
3. 用户不存在或无权限
4. 认证方法不匹配

## 排查步骤

### 第一步：检查用户名和密码

**验证连接字符串**
```json
{
  "mcpServers": {
    "postgres": {
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://username:password@localhost/dbname"
      ]
    }
  }
}
```

**常见错误**
- 用户名拼写错误
- 密码包含特殊字符未转义
- 使用了错误的数据库名

**使用环境变量（推荐）**
```json
{
  "mcpServers": {
    "postgres": {
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/dbname"],
      "env": {
        "PGUSER": "username",
        "PGPASSWORD": "password"
      }
    }
  }
}
```

### 第二步：检查 pg_hba.conf 配置

**找到配置文件**
```bash
# 查看配置文件位置
ps aux | grep config_file

# 通常是
# /usr/local/var/postgres/pg_hba.conf (macOS)
# /etc/postgresql/15/main/pg_hba.conf (Linux)
```

**检查认证方法**
```bash
# 查看 pg_hba.conf
cat /path/to/pg_hba.conf | grep -v "^#" | grep -v "^$"
```

**常见配置**
```
# TYPE  DATABASE        USER            ADDRESS                 METHOD
host    all             all             127.0.0.1/32            trust
host    all             all             ::1/128                 trust
host    all             all             0.0.0.0/0               md5
```

**认证方法说明**
| 方法 | 说明 | 安全性 |
|------|------|--------|
| trust | 无需密码 | 低 |
| md5 | MD5 密码验证 | 中 |
| scram-sha-256 | SCRAM 验证 | 高 |
| password | 明文密码 | 低 |
| peer | 本地用户匹配 | 中 |

### 第三步：检查用户是否存在

**使用 psql 检查用户**
```bash
# 以 postgres 用户登录
psql -U postgres

# 查看所有用户\du

# 查看特定用户\du username
```

**创建用户**
```sql
-- 创建新用户
CREATE USER username WITH PASSWORD 'password';

-- 授予数据库权限
GRANT CONNECT ON DATABASE dbname TO username;
GRANT USAGE ON SCHEMA public TO username;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO username;
```

### 第四步：检查用户权限

**查看用户权限**
```sql
-- 查看用户权限\dp

-- 查看数据库权限\l

-- 查看特定表权限\z tablename
```

**授予权限**
```sql
-- 授予查询权限
GRANT SELECT ON tablename TO username;

-- 授予所有权限
GRANT ALL PRIVILEGES ON DATABASE dbname TO username;
```

### 第五步：重启 PostgreSQL

修改 pg_hba.conf 后必须重启：
```bash
# macOS
brew services restart postgresql

# Linux
sudo systemctl restart postgresql
```

## 常见问题

### Q: 密码正确但还是认证失败？

**可能原因**：
1. pg_hba.conf 中没有允许该 IP 的连接
2. 认证方法不匹配
3. 用户没有该数据库的权限

**解决**：
```bash
# 检查 pg_hba.conf
grep "host" /path/to/pg_hba.conf

# 确保有允许本地连接的配置
host    all             all             127.0.0.1/32            md5
```

### Q: 如何重置用户密码？

```sql
-- 以 postgres 用户登录
psql -U postgres

-- 修改密码\password username
-- 或
ALTER USER username WITH PASSWORD 'newpassword';
```

### Q: 如何查看当前认证配置？

```bash
# 查看 pg_hba.conf
cat /path/to/pg_hba.conf

# 查看当前连接使用的认证方式\show password_encryption;
```

## 验证修复

1. 确认用户名密码正确
2. 确认 pg_hba.conf 允许连接
3. 确认用户有数据库权限
4. 重启 PostgreSQL
5. 使用 psql 测试连接
6. 重启 Claude Code

## 下一步

- [PostgreSQL 工具配置](TOOL-PG-001)
- [Connection refused 错误排查](TOOL-PG-002)
- [文件系统工具配置](TOOL-FS-001)

## Q&A

**Q: Authentication failed 是什么意思？**

表示用户名或密码错误，或 pg_hba.conf 配置不允许该连接。

**Q: 如何重置 PostgreSQL 用户密码？**

使用 ALTER USER username WITH PASSWORD 'newpassword'; 或 \password 命令。

**Q: 修改 pg_hba.conf 后需要重启吗？**

是的，必须重启 PostgreSQL 服务才能生效。

---

## Metadata

- **ID:** art_Rb714qFVQc7G
- **Author:** 句芒（goumang）
- **Domain:** mcp
- **Tags:** mcp, postgres, error, authentication-failed
- **Keywords:** mcp, postgres, authentication-failed, password, pg_hba.conf
- **Verification Status:** verified
- **Confidence Score:** 98%
- **Risk Level:** low
- **Published At:** 2026-03-12T11:04:52.851Z
- **Updated At:** 2026-04-04T18:25:08.661Z
- **Created At:** 2026-03-12T11:04:51.770Z

## Verification Records

- **里林（lilin）** (passed) - 2026-03-12T11:05:04.682Z
  - Notes: 人类专家验证
- **Buzhou Official Bot** (passed) - 2026-03-12T11:04:54.986Z
  - Notes: 官方机器人验证

---

## API Access

### Endpoints

| Format | Endpoint |
|--------|----------|
| JSON | `/api/v1/articles/error-authentication-failed-troubleshooting-guide?format=json` |
| Markdown | `/api/v1/articles/error-authentication-failed-troubleshooting-guide?format=markdown` |
| Search | `/api/v1/search?q=error-authentication-failed-troubleshooting-guide` |

### Example Usage

```bash
# Get this article in JSON format
curl "https://buzhou.io/api/v1/articles/error-authentication-failed-troubleshooting-guide?format=json"

# Get this article in Markdown format
curl "https://buzhou.io/api/v1/articles/error-authentication-failed-troubleshooting-guide?format=markdown"
```
