Ошибка аутентификации Postgres org.postgresql.util.PSQLException: FATAL: Ident authentication failed for user*
1) Первое что следует сделать – проверить пароль пользователя БД и его соответствие в параметрах подключения
2) Второе, если первое не помогло – попробовать изменить настройки доступа в файле конфигурации Postgres – pg_hba.conf,
например(в зависимости от ОС место установки может различаться) путь к нему может быть таким: /var/lib/pgsql/data/pg_hba.conf
значения по умолчанию:
И перезагрузим конфиг Postgres
Проверим соединение: если ошибка пропала, то проблема выявлена и нам необходимо настроить доступ(нам может понадобиться удаленное соединение с БД, а также по причинам безопасности, нас такое решение может не устраивать).
Восстановим значения доступа в файле pg_hba.conf
- Документация нам говорит:
- Файл pg_hba.conf
- psql: FATAL: Ident authentication failed for user «postgres»
- Re: psql: FATAL: Ident authentication failed for user «postgres»
- Re: psql: FATAL: Ident authentication failed for user «postgres»
- Re: psql: FATAL: Ident authentication failed for user «postgres»
- Re: psql: FATAL: Ident authentication failed for user «postgres»
- 22 Answers 22
Документация нам говорит:
“[…]Аутентификация – процесс при котором сервер базы данных идентифицирует клиента, а также определяет разрешено ли клиентскому приложению(или пользователю запускающему клиентское приложение) соединяться с сервером по требующемуся имени пользователя БД.
PostgreSQL предлагает несколько разных методов клиентской аутентификации. Метод используемый для аутентификации соединения определенного клиента может быть основан на адресе хоста(клиента), настройках базы данных и пользователе.
Имя пользователя базы данных PostgreSQL логически отличается от имени пользователя в операционной системе, на которой работает сервер. Если все пользователи какого-то сервера также имеют аккаунты в его операционной системе имеет смысл назначать имена пользователей БД, которые бы совпадали с именами пользователей в операционной системе. Однако сервер БД который принимает удаленные подключения может иметь много пользователей БД, которые не имеют аккаунтов в ОС, в таком случае, конечно, нам не требуется соответствий имен пользователей БД и пользователей ОС.”
Файл pg_hba.conf
Клиентская аутентификация контроллируется конфигурационным файлом, традиционно именуемым pg_hba.conf и расположенным в папке с кластером баз – data.(HBA stands for host-based authentication.) Файл по умолчанию pg_hba.conf создается, когда каталог data создается с помощью команды initdb. Файл можно располагать где угодно, однако следует не забывать про конфигурацию параметров в файле hba_file.
Формат файла pg_hba.conf подразумевает набор записей на каждой строке. Пустые строки игнорируются как и закомментированные с помощью #.
Перенос срок запрещен. “Запись” состоит из полей отделенных пробелами или табуляцией. Поля могут содержать неразрывные пробелы(white-space – несколько пробелов как один) если значение поля заключено в двойные кавычки. Заключение в кавычки одного из ключевых слов в полях database, user, или address (например all или replication) приводит к потере ключевым словом значения, и просто приводит к тому что database читается как имя базы “database”, user – имя пользователя – “user” и т.д.
Каждая запись определяет тип соединения, диапазон IP-адресов(если они подходят по типу соединения), имя базы данных, имя пользователя и метод аутентификации для установления соединений по указанным параметрам. Первая же запись подходящая по параметрам адреса, имени базы, имени пользователя и т. д. используется для реализации аутентификации. Причем(!) если аутентификация по данной записи не проходит, не осуществляется никаких проверок и других попыток провести аутентификацию с помощью других записей.
Если ни одна запись не соответствует параметрам соединения – соединение запрещается.[…]”
Итак, нам необходимо создать запись для нашего подключения и перегрузить конфиг Postgres, что и сделаем
мы читаем про разные типы аутентификации и обнаруживаем md5 – аутентификация по паролю, это нам подходит, –
изменяем запись(или создаем новую запись и располагаем ее над остальными(так как порядок записей/строк имеет значение!))
psql: FATAL: Ident authentication failed for user «postgres»
I am having problems logging into psql as a non-‘postgres’ user.
/home/djoo[5:38pm]$ %psql kermit -U postgres
psql: FATAL: Ident authentication failed for user «postgres»
Below is a portion of the pg_hba.conf file, which I believe is configured so that a password is not required.
# TYPE DATABASE USER CIDR-ADDRESS METHOD
# «local» is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
Any suggestions would be greatly appreciated!
Re: psql: FATAL: Ident authentication failed for user «postgres»
Re: psql: FATAL: Ident authentication failed for user «postgres»
Re: psql: FATAL: Ident authentication failed for user «postgres»
Always cc the mailing list so others can provide other suggestions where
necessary.
Dan Joo wrote:
> Thanks, Chris, but yes, I am sure that there is no such line. (see below)
>
> [root@RH-Dev data]# cat pg_hba.conf | grep -v ‘^#’
>
>
>
>
>
> local all all trust
> host all all 127.0.0.1/32 trust
> host all all ::1/128 trust
>
> Dan
Did you HUP postmaster?
The docs say you can just pg_ctl reload to do this.
> ——Original Message——
> From: Chris [mailto:]
> Sent: Monday, May 19, 2008 6:22 PM
> To: Dan Joo
> Cc:
> Subject: Re: [GENERAL] psql: FATAL: Ident authentication failed for user «postgres»
>
> Dan Joo wrote:
>> Hi everyone,
>>
>>
>>
>> I am having problems logging into psql as a non-‘postgres’ user.
>>
>>
>>
>> */home/djoo[5:38pm]$ %psql kermit -U postgres*
>>
>> *psql: FATAL: Ident authentication failed for user «postgres»*
>
> Sure there isn’t a line like this:
>
> local all postgres ident sameuser
>
> uncommented?
>
> $ cat /path/to/pg_hba.conf | grep -v ‘^#’
>
> Normally the ‘postgres’ user is ‘ident’ only unless you remove (or
> comment out) that particular line, then restart postgres.
>
Re: psql: FATAL: Ident authentication failed for user «postgres»
It is Linux. I am trying to login as postgres but as a user not in the database. This is because I will be creating a web front end, and various users, not registered in the database, will need to access the database. Thus, as “postgres” I can log in fine:
bash-3.1$ psql kermit -U postgres
Welcome to psql 8.1.11, the PostgreSQL interactive terminal.
Type: copyright for distribution terms
h for help with SQL commands
? for help with psql commands
g or terminate with semicolon to execute query
But as myself, I can’t.
/home/djoo[8:25am]$ %psql kermit -U postgres
psql: FATAL: Ident authentication failed for user «postgres»
This is pretty much the same setup I had with another company, so I am confused why I can’t access. Is there another file that I need to alter besides the pg_hba.conf file?
Thanks for your help,
From: Luigi Castro Cardeles [mailto:]
Sent: Tuesday, May 20, 2008 5:53 AM
To: Dan Joo
Subject: Re: [GENERAL] psql: FATAL: Ident authentication failed for user «postgres»
what’s your machine configuration? Linux, Mac Os?
if you are using mac, maybe you have a problem with identd.
I have installed PostgreSQL and pgAdminIII on my Ubuntu Karmic box.
I am able to use pgAdminIII successfully (i.e. connect/log on), however when I try to login to the server using the same username/pwd on the command line (using psql), I get the error:
Does anyone now how to resolve this issue?
22 Answers 22
Did you set the proper settings in pg_hba.conf?
The following steps work for a fresh install of postgres 9.1 on Ubuntu 12.04. (Worked for postgres 9.3.9 on Ubuntu 14.04 too.)
By default, postgres creates a user named ‘postgres’. We log in as her, and give her a password.
Logout of psql by typing q or ctrl+d . Then we connect as ‘postgres’. The -h localhost part is important: it tells the psql client that we wish to connect using a TCP connection (which is configured to use password authentication), and not by a PEER connection (which does not care about the password).
Edit the file /etc/postgresql/8.4/main/pg_hba.conf and replace ident or peer by either md5 or trust , depending on whether you want it to ask for a password on your own computer or not. Then reload the configuration file with:

You’re getting this error because you’re failing client authentication. Based on the error message, you probably have the default postgres configuration, which sets client authentication method to «IDENT» for all PostgreSQL connections.
You should definitely read section 19.1 Client Authentication in the PostgreSQL manual to better understand the authentication settings available (for each record in pg_hba.conf), but here is the relevant snippet to help with the problem you’re having (from the version 9.5 manual):
Allow the connection unconditionally. This method allows anyone that can connect to the PostgreSQL database server to login as any PostgreSQL user they wish, without the need for a password or any other authentication. See Section 19.3.1 for details.
reject
Reject the connection unconditionally. This is useful for «filtering out» certain hosts from a group, for example a reject line could block a specific host from connecting, while a later line allows the remaining hosts in a specific network to connect.
md5
Require the client to supply a double-MD5-hashed password for authentication. See Section 19.3.2 for details.
password
Require the client to supply an unencrypted password for authentication. Since the password is sent in clear text over the network, this should not be used on untrusted networks. See Section 19.3.2 for details.
gss
Use GSSAPI to authenticate the user. This is only available for TCP/IP connections. See Section 19.3.3 for details.
sspi
Use SSPI to authenticate the user. This is only available on Windows. See Section 19.3.4 for details.
ident
Obtain the operating system user name of the client by contacting the ident server on the client and check if it matches the requested database user name. Ident authentication can only be used on TCP/IP connections. When specified for local connections, peer authentication will be used instead. See Section 19.3.5 for details.
peer
Obtain the client’s operating system user name from the operating system and check if it matches the requested database user name. This is only available for local connections. See Section 19.3.6 for details.
ldap
Authenticate using an LDAP server. See Section 19.3.7 for details.
radius
Authenticate using a RADIUS server. See Section 19.3.8 for details.
cert
Authenticate using SSL client certificates. See Section 19.3.9 for details.
pam
Authenticate using the Pluggable Authentication Modules (PAM) service provided by the operating system. See Section 19.3.10 for details.
So . to solve the problem you’re experiencing, you could do one of the following:
Change the authentication method(s) defined in your pg_hba.conf file to trust , md5 , or password (depending on your security and simplicity needs) for the local connection records you have defined in there.
Update pg_ident.conf to map your operating system users to PostgreSQL users and grant them the corresponding access privileges, depending on your needs.
Leave the IDENT settings alone and create users in your database for each operating system user that you want to grant access to. If a user is already authenticated by the OS and logged in, PostgreSQL won’t require further authentication and will grant access to that user based on whatever privileges (roles) are assigned to it in the database. This is the default configuration.