刚开始接触 PostgreSQL, 安装后就有一个默认用户 postgres, 而且在启动 PostgreSQL 后只能通过切换到 Linux 的 postgres 用户才能登录数据库进行操作, 和 MySQL 的登录认证居然不一样. 查了好多资料才知道, 原来有个 pg_hba.conf 的配置文件作登录限制. 它的语法规则是这样的:
- local database user auth-method [auth-options]
- host database user address auth-method [auth-options]
- hostssl database user address auth-method [auth-options]
- hostnossl database user address auth-method [auth-options]
- host database user IP-address IP-mask auth-method [auth-options]
- hostssl database user IP-address IP-mask auth-method [auth-options]
- hostnossl database user IP-address IP-mask auth-method [auth-options]
第一列是连接的方式, local 是通过本地的 unix socket 连接, host 是通过 IP 地址连接. 第二列是目标数据库, 第三列是用户. 最后一列是认证方式 (关键点), 总共支持 11 种认证方式:
- Trust Authentication
- Password Authentication
- GSSAPI Authentication
- SSPI Authentication
- Ident Authentication
- Peer Authentication
- LDAP Authentication
- RADIUS Authentication
- Certificate Authentication
- PAM Authentication
- BSD Authentication
其中最常见的就是 peer,ident,password.
peer 方式中, client 必须和 PostgreSQL 在同一台机器上, 并且需要当前系统用户和要登陆到 PostgreSQL 的用户名相同, 就可以登陆.
ident 与 peer 类似, 不过 peer 只能在 PostgreSQL 本地使用, ident 则可以跨主机使用.
其实我们最常用的方式是通过密码远程登陆:
password 认证分为三种方式: scram-sha-256,md5,password.
这三种方式都用密码认证, 区别是密码在 PostgreSQL 上存储的形式和登陆时密码的传输形式.
如:# IPv4 local connections: host all all 127.0.0.1/32 md5
注意: 修改了 pg_hba.conf 之后, 需要重启 PostgreSQL, 才会应用新配置.
来源: http://www.linuxidc.com/Linux/2019-03/157516.htm