背景:PostgreSQL 新建数据库用户后切换用户报错、重新指定新用户登录也报错,但postgres用户登录没有问题。
postgres用户登录数据库
# su - postgres
-bash-4.2$ psql -U postgres -d postgres
创建数据库用户test & 创建数据库testdb01 & 授权
postgres=# CREATE USER test WITH PASSWORD '1q2w3e';
postgres=# CREATE DATABASE testdb01 OWNER test;
postgres=# GRANT ALL PRIVILEGES ON DATABASE testdb01 TO test;
切换用户到test时报错:
postgres=# \c - test
FATAL: Peer authentication failed for user "test"
Previous connection kept
postgres=# \c testdb01
You are now connected to database "testdb01" as user "postgres".
testdb01=# \c - test
FATAL: Peer authentication failed for user "test"
Previous connection kept
testdb01=# \q
-bash-4.2$ psql -U test -d testdb01
psql: error: FATAL: Peer authentication failed for user "test"
但是以postgres用户可以正常登录:
-bash-4.2$ psql -U postgres -d testdb01
psql (12.9)
Type "help" for help.
testdb01=#
报错的原因:
psql的连接建立于Unix Socket上默认使用peer authentication,所以必须要用和数据库用户相同的系统用户进行登录。
解决方法:
将peer authentiction 改为 md5,并给数据库设置密码。修改配置文件/var/lib/pgsql/12/data/pg_hba.conf,将
local all all peer
两行配置的peer改成md5,修改后的内容如下:
local all all md5
生效配置:
service postgresql-12 reload
再次尝试以新用户登录成功:
-bash-4.2$ psql -U test -d testdb01
Password for user test:
psql (12.9)
Type "help" for help.
testdb01=>
testdb01=> \c - postgres
Password for user postgres:
You are now connected to database "testdb01" as user "postgres".
testdb01=#
testdb01=# \c - test
Password for user test:
You are now connected to database "testdb01" as user "test".
testdb01=>