PostgresSQLでユーザー作った後にパスワードを設定してアクセスしようとする以下のエラーが出てくる。
psql: FATAL: Peer authentication failed for user "YOUR_ROLE"
Peer authentication failed の原因
エラーコード通りだが、peer認証がオンになっているためこのエラーが発生しています。
peer認証とはPostgresのデフォルトの認証方法で、OS側のユーザー名とPostgreSQL側のユーザー名が一致していないと発生するエラーです。
デフォルトの状態であれば、以下の通りだとPeer認証のエラーが発生せずPostgresへログインすることが可能です。
$ su - postgres
$ psql
postgres=#
しかしこの状態だと2つの問題があります。
- 毎回Postgresユーザーへならないといけない。
- Postgresの別ユーザーを作ってもアクセスできない。
上記を解決したい。
Peer authentication failedを発生させないための対応
PostgreSQL9.6を使っています。
/etc/postgresql/9.6/main/pg_hba.conf を編集します。
今回はpeer認証ではなく、全てのユーザーをパスワード認証へ変更します。そのため、先にpostgresユーザーへパスワードも設定しておきましょう。
su - postgres
psql
postgres=# Alter Role postgres with password 'YOUR_PASSWORD';
# DO NOT DISABLE!
# If you change this first entry you will need to make sure that the
# database superuser can access the database using some other method.
# Noninteractive access to all databases is required during automatic
# maintenance (custom daily cronjobs, replication, and similar tasks).
#
# Database administrative login by Unix domain socket
# ↓コメントアウト
#local all postgres peer
# ↓追加
local all postgres md5
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
# ↓コメントアウト
#local all all peer
# ↓追加
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
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local replication postgres peer
#host replication postgres 127.0.0.1/32 md5
#host replication postgres ::1/128 md5
対応は以上です。
コメントにも書いている通り、以下の2行がpeer認証を設定しています。
local all postgres peer
local all all peer
これを今回はmd5と設定しました。