刚开始接触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种认证方式:

  1. Trust Authentication

  2. Password Authentication

  3. GSSAPI Authentication

  4. SSPI Authentication

  5. Ident Authentication

  6. Peer Authentication

  7. LDAP Authentication

  8. RADIUS Authentication

  9. Certificate Authentication

  10. PAM Authentication

  11. 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,才会应用新配置。