Psql ошибка пользователь не прошел проверку подлинности

Поставил postgresQL на свой пк (Windows). Учусь всякие штуки делать на nestjs. Нужна именно эта база. Проблема: захожу в терминале предварительно выбрав папку где лежит psql

.\psql -v

на что мне терминал отвечает:

Пароль пользователя Admin:

Ввожу пароль от своего аккаунта на ПК. И происходит ошибка:

psql: ошибка: подключиться к серверу «localhost» (127.0.0.1), порту
5432 не удалось: ВАЖНО: пользователь «Admin» не прошёл проверку
подлинности (по паролю)

Думал может не на той раскладке или Nun Lock зажат. все проверил.
В итоге решил зайти через pgAdmin4 — та же база, только в виде программы с интерфейсом под windows.
Просит пароль. ввожу тот же пароль, все нормально работает.
Нужно именно из строки как то заходить. Есть мысли что не так?

задан 18 янв 2022 в 10:53

Андрей's user avatar

pgAdmin -> там вводишь свой пароль и появится стандартное окно Welcome -> в Quick Links будет Add New Server -> там заполняешь и сохраняешь (не обязательно всё, можно заполнить только General, Connetcion). Теперь в консоли сможешь подключаться к нему. (На всякий случай поясню. При подключение используешь имя и пароль, которые задавал при создании этого сервера)

ответ дан 10 мая 2022 в 10:49

Akayo's user avatar

тоже была такая проблема, с паролем и не находил путь.

решение:

  1. прописал путь в переменных средах.
  2. Работает только через командную строку, через PowerShell не работает (у меня)

aleksandr barakin's user avatar

ответ дан 4 ноя 2022 в 21:15

Andryu's user avatar

2

Выполни в консоли:
psql -U postgres
затем введи пароль, который вводил, когда заходил через pgAdmin4. Должно помочь.
Через консоль ты логинешься через системную учетку, которой нет в postgres.
Команда «psql -U USERNAME» позволяет авторизоваться под учеткой USERNAME.
Надеюсь поможет.

ответ дан 26 дек 2022 в 19:27

Romul Fobos's user avatar

Solution of psql: FATAL: Peer authentication failed for user “postgres” (or any user)

The connection failed because by default psql connects over UNIX sockets using peer authentication, that requires the current UNIX user to have the same user name as psql. So you will have to create the UNIX user postgres and then login as postgres or use sudo -u postgres psql database-name for accessing the database (and psql should not ask for a password).

If you cannot or do not want to create the UNIX user, like if you just want to connect to your database for ad hoc queries, forcing a socket connection using psql --host=localhost --dbname=database-name --username=postgres (as pointed out by @meyerson answer) will solve your immediate problem.

But if you intend to force password authentication over Unix sockets instead of the peer method, try changing the following pg_hba.conf* line:

from

# TYPE DATABASE USER ADDRESS METHOD
local  all      all          peer

to

# TYPE DATABASE USER ADDRESS METHOD
local  all      all          md5
  • peer means it will trust the identity (authenticity) of UNIX user. So not asking for a password.

  • md5 means it will always ask for a password, and validate it after hashing with MD5.

  • trust means it will never ask for a password, and always trust any connection.

You can, of course, also create more specific rules for a specific database or user, with some users having peer and others requiring passwords.

After changing pg_hba.conf you’ll need to restart PostgreSQL if it’s running. E.g. sudo service postgresql restart

Steps to change/create default postgres user’s password:
  1. trust connection by adding in pg_hba.conf file
  • local all postgres trust
  1. Restart postgresql service
  • sudo service postgresql restart
  1. psql -U postgres

  2. At the postgres=# prompt, change the user name postgres password:

  • ALTER USER postgres with password ‘new-password’;
  1. Revert the changes in pg_hba.conf file from trust to md5 and restart postgresql.
pg_hba.conf file location

The file pg_hba.conf will most likely be at /etc/postgresql/9.x/main/pg_hba.conf
To check location of pg_hba.conf connect to postgres db using psql then type SHOW hba_file; command.

After change pg_hba.conf file, you can execute SELECT pg_reload_conf(); or pg_ctl reload with superuser instead of restart postgresql service.

* Source

Say you’re seeing this message:

FATAL:  Ident authentication failed for user "..."

What are the causes of this error message?

Cristian Ciupitu's user avatar

asked Jul 11, 2012 at 0:44

Steve Bennett's user avatar

Steve BennettSteve Bennett

5,78012 gold badges47 silver badges59 bronze badges

It means that Postgres is trying to authenticate a user using the Ident protocol, and can’t. Ident auth automatically matches Unix usernames with Postgres usernames. It works like this:

  • You have database role ‘foo’ on database ‘db’
  • Your pg_hba.conf file (in /etc/postgres-something/main) defines ‘Ident’ as the protocol to connect to database db for users connecting from certain hosts
  • The unix username making the connection is ‘foo’
  • An Ident server running on the machine the user is connecting from confirms that their username really is ‘foo’

Possible causes and solutions:

  1. There is no Ident server running on the machine you’re trying to connect from. Test this by trying to connect to it on port 113. If that fails, install an Ident server (eg, sudo apt-get install oidentd).

  2. There’s an Ident server, but there’s no database role matching the name you’re trying to connect with (‘foo’ in the above example). So create it by connecting somehow to the database with superuser rights and do CREATE ROLE foo. Alternatively add an entry to /etc/postgresql/.../main/pg_ident.conf (or /var/lib/pgsql/12/data or wherever).

  3. Maybe the shell username doesn’t match the database role. You may be able to test this by connecting to the Ident server while a connection is going on, and passing the right port numbers.

  4. Maybe you actually want to connect with a password, not Ident. Edit the pg_hba.conf file appropriately. For example, change:

    host all all 127.0.0.1/32 ident
    

to

    host all all 127.0.0.1/32 md5

Be sure to restart Postgres after updating the pg_hba.conf file. You do that by issuing the following command:

    sudo service postgresql-12 restart
   

answered Jul 11, 2012 at 0:44

Steve Bennett's user avatar

Steve BennettSteve Bennett

5,78012 gold badges47 silver badges59 bronze badges

8

Not sure about the causes, but this fixed it for me:

in pg_hba.conf

change to this:

host all all 127.0.0.1/32 md5

Exact error: Caused by: org.postgresql.util.PSQLException: FATAL: Ident authentication failed for user "postgres"

answered Sep 10, 2012 at 15:21

jacktrades's user avatar

1

For Centos 7, Change pg_hba.conf to below:

# TYPE  DATABASE        USER            ADDRESS                 METHOD

# "local" is for Unix domain socket connections only
local   all             all                                     peer
# IPv4 local connections:
#host    all             all             127.0.0.1/32            ident
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
#host    all             all             ::1/128                 ident
host    all             all             ::1/128                 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local   replication     all                                     peer
#host    replication     all             127.0.0.1/32            ident
#host    replication     all             ::1/128                 ident

Demur Rumed's user avatar

answered Apr 9, 2020 at 7:00

KulJeet's user avatar

KulJeetKulJeet

511 silver badge1 bronze badge

0

On CentOS, add the following line to /var/lib/pgsql/9.3/data/pg_hba.conf:

host all all 127.0.0.1/32 trust

And comment out the other entries.

Of course, this setting is not secure, but if you’re just messing about on a development VM like me then it’s probably fine…

answered Jul 14, 2014 at 11:11

XåpplI'-I0llwlg'I  -'s user avatar

0

Try to use -h 127.0.0.1 instead of -h localhost

answered May 27, 2021 at 13:55

despotbg's user avatar

If you have not tried this already, review your pg_hba.conf file. It will be named something like /var/lib/pgsql/9.3/data/pg_hba.conf (Fedora 20); you may have to use ‘find / -name pg_hba.conf’ to locate it.

At the bottom of the file, change the ‘METHOD’ values to ‘trust’ for local testing (see postgres docs for full information). Reboot the machine to ensure everything is started clean and the new params are read.

Hopefully this will cure your woes. It solved my problems on Fedora 20 with PostgreSQL 9.3.

answered Jul 26, 2014 at 0:59

Alan Thompson's user avatar

1

You must log in to answer this question.

Not the answer you’re looking for? Browse other questions tagged

.

For those of you who got this error and NONE of these answers helped, I may not have StackOverflow fish for you, but I’ll teach you how to fish!

You likely don’t have the correct order of lines in the pg_hba.conf file. If you read this PostgreSQL documentation link below, it says this error can be thrown if «no matching entry is found». However, that is NOT always true! Documentation is written by humans and humans make mistakes.

https://www.postgresql.org/docs/current/client-authentication-problems.html

The truth is that a line further up might take precedence, is qualifying and is forcing you to use a password stored in PostgreSQL rather than delegated authentication or some other method. If you are not specifying a password stored in PostgreSQL, then you do not need the LOGIN role attribute. Put a line at the very top of this list with your specific user, authentication protocol, network details and other criteria. Also, many may think that most computers use IPv4. Try IPv6 and you’ll be surprised. Once you know the very specific criteria of your issue and place a line at the top, then you have established the ONLY RELIABLE WAY to troubleshoot these pg_hba.conf issues without source code debugging!

Another helpful trick is to create a crapload of Server entries in pg_admin (SQL IDE for PostgreSQL) with all of your users and authentication protocols for testing. When you test different scenarios, you’ll instantly know which ones fail.

Also, whenever you change this file, restart the PostgreSQL service, before testing the user.

You’re welcome my friend. :)

I just installed PostgreSQL 9.4 on Ubuntu 15.10.

  1. I created a user with createuser -P myuser
  2. I created a database with createdb -O myuser mydatabase
  3. I edited pg_hba.conf and added local mydatabase myuser md5
  4. I restarted PostgreSQL with sudo service postgresql restart

User myuser is a PostgresSQL user only and has no user account on Ubuntu.

When I try to connect to the database with psql -W mydatabase myuser it fails with psql: FATAL: Peer authentication failed for user "myuser".

PostgreSQL is running …

● postgresql.service - PostgreSQL RDBMS
   Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset: enabled)
   Active: active (exited) since Thu 2016-03-03 09:53:00 CET; 9min ago
  Process: 22219 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
 Main PID: 22219 (code=exited, status=0/SUCCESS)

Mar 03 09:53:00 SERVER01 systemd[1]: Starting PostgreSQL RDBMS...
Mar 03 09:53:00 SERVER01 systemd[1]: Started PostgreSQL RDBMS.

… and listening.

Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:postgresql    *:*                     LISTEN
tcp6       0      0 localhost:postgresql    [::]:*                  LISTEN
Active UNIX domain sockets (only servers)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     151534   /var/run/postgresql/.s.PGSQL.5432

What do I have to do to connect with user myuser to database mydatabase?

Evan Carroll's user avatar

Evan Carroll

61.4k45 gold badges229 silver badges462 bronze badges

asked Mar 3, 2016 at 9:06

Daniel's user avatar

In a fresh install from a few days ago, the second line of my pg_hba.conf is

local   all             all              peer

I believe this is the one that makes your connection attempt fail.

The order of rules matter here: the first one that matches the access method, username, database name and source IP range will be considered. If it fails, then there is no second try, so the connection attempt will likely fail. Or, as the documentation states:

There is no «fall-through» or «backup»: if one record is chosen and the authentication fails, subsequent records are not considered. If no record matches, access is denied.

The solution is easy: either remove the above line if you don’t plan to use peer authentication, or move your specific rule above this one.

Evan Carroll's user avatar

Evan Carroll

61.4k45 gold badges229 silver badges462 bronze badges

answered Mar 3, 2016 at 9:16

dezso's user avatar

dezsodezso

30.7k13 gold badges98 silver badges144 bronze badges

2

First of all, check if you have the lines giving permission to the myuser user in pg_hba.conf. For example:

# IPv4 local connections:
host    all             all             127.0.0.1/32            md5
# IPv6 local connections:
host    all             all             ::1/128                 md5

Or any other lines of permission to IPV4 (and IPv6 if you use) with: TYPE DATABASE USER ADDRESS METHOD

After this check, run the psql as follows:

psql -h localhost -U myuser mydatabase

And then, the requested prompt, enter the user’s password myuser.

aakaasaraamanna's user avatar

answered Mar 4, 2016 at 14:52

Alvaro Neto's user avatar

2

Понравилась статья? Поделить с друзьями:
  • Psql ошибка подключиться к серверу через сокет
  • Psql ошибка отношение не существует
  • Python exception вывести ошибку
  • Psql ошибка не удалось подключиться к серверу
  • Psql ошибка база данных не существует