How to configure postgresql so it accepts login+password auth? - postgresql

I have a fresh ubuntu 10.10 install with all updates and postgresql 8.4
In order for postgresql to accept login+password connections i have configured it via:
sudo su postgres
psql
ALTER USER postgres WITH PASSWORD 'password';
CREATE DATABASE myapp;
\q
exit
sudo vi /etc/postgresql/8.4/main/pg_hba.conf
change "local all all indent" to "local all all trust"
But, surprisingly, this is not working! The command
psql -U postgres password
Evaluates with error:
psql: FATAL: Ident authentication failed for user "postgres"
Any hints how i can make the psql -U to work?

It is probably a good idea to leave the "postgres" user with ident authentication. By default I believe Ubuntu uses the "postgres" user to perform upgrades, backups, etc, and that requires that it is able to login without a specified password.
I recommend creating another user (probably with your own username) and giving it admin privileges as well. Then you can use that user with passwords on local connections.
Here is what the relevant parts of my pg_hba.conf look like:
# allow postgres user to use "ident" authentication on Unix sockets
# (as per recent comments, omit "sameuser" if on postgres 8.4 or later)
local all postgres ident sameuser
# allow all other users to use "md5" authentication on Unix sockets
local all all md5
# for users connected via local IPv4 or IPv6 connections, always require md5
host all all 127.0.0.1/32 md5
host all all ::1/128 md5
Also note that psql -U postgres password will not do what you want. The password should never be specified on the commandline. That will try to login as user "postgres" to a database named "password".
You should use psql -U postgres myapp instead. Postgres will automatically prompt you for a password, if it is configured properly to require one.
In case we want the password be filled-in automatically, place it in $HOME/.pgpass file

I think your pg_ident.conf file is misconfigured. Also, have you tried
psql -U postgres -W

Another thing that can cause this is expired credentials. I don't think this happened in version 8, but in version 9 when you create a new role in pgadmin, it is created in an expired state and you need to change or clear the role's expiration date before you will be able to login with it.

You may find it helpful to create the database's user and schema in PostgreSQL:
Log into PostgreSQL from the postgres user
$ sudo -u postgres psql postgres
Once in, create the user and database
CREATE ROLE myuser LOGIN PASSWORD 'mypass';
CREATE DATABASE mydatabase WITH OWNER = myuser;
Log into PostgreSQL from the new user account
$ psql -h localhost -d mydatabase -U myuser -p <port>

Related

psql: FATAL: password authentication failed for user "postgres" postgresql version 10

I recently installed Postgre version 10 on a linux red hat. I'm trying to configure that psql will prompt a user for password when accessing the database. After changing everything to scram-sha-256. I'm getting this error when accessing psql
psql: FATAL: password authentication failed for user "postgres"
This is my pg_hba.conf:
Any idea how can I fix this? Thanks!
Postgres store password md5 format as default. If you want to change password encryption you have to follow bellow solution:
P.S: Before start, You have to undo pg_hba.conf file authenticate method to md5
Edit postgresql.conf and change password_encryption to
password_encryption = scram-sha-256
Restart Postgres service (or reload service)
reset the user password
# if use psql cli
\password <user>
# If use SQL command
alter user <user> with password '<password>';
After updating all passwords you should change pg_hba.conf authenticate method to scram-sha-256 and reset service again
Reference: Information about upgrade postgres password authenicate
I know that something that solved to me was in setting a new password (in CMD) when it was necessary to give a password for psql to be recognized:
set PGPASSWORD= #type here the password you want to set
After setting, you write the following (for example):
psql -h 188.81.81.92 -U postgres -d postgres -p 5432
where -h stands for host, -U for user, -d for the database root, -p for port, using the postgreSQL language.
In windows, it could happen to outcome a problem: error: connection to server (...), which can be solved by typing:
C:\\Program Files\\PostgreSQL\\14\\bin\\psql.exe
this is, you open the file psql.exe and it will work fine.

Can't access psql due to authentication fail

I'm trying a tutorial for django that it uses postgresql but I have some issues in setting up the DB. I did change postgres password using sudo passwd postgres and I can login to postgres account using su postgres or sudo su - postgres but after that I can't access the postgres prompt with pqsl. It gives me the following error:
psql: FATAL: password authentication failed for user "postgres"
I've changed the pg_hba.conf file too (from peer to md5) but it didn't change anything.
I've never worked with postgresql and this is my first time using it so if you need any other information please ask me.
sudo passwd postgres is for the system user postgres which is why you can su to system user postgres shell. When you are doing psql -U postgres you are logging in as database user postgres. That is a different account. It is convention that the system user the Postgres server runs as is generally called postgres. Also by convention the Postgres server database 'root/superuser' is the name of the user that the server runs as, so again generally postgres. If you want to log in as postgres user to server using password you will need to create a password for the database user postgres. To do that I would see if in pg_hba.conf the local (not localhost) line is set to trust. If not set it to that and and do:
psql -U postgres -d postgres
Do not specify a -h. This will connect you via a local socket. Then you can :
https://www.postgresql.org/docs/12/sql-alteruser.html
ALTER USER postgres WITH PASSWORD 'your_password'
This will create a password for postgres user.
FYI, you don't have to log into system user postgres account to work as postgres user in database. All you have to do is specify -U postgres to any of the Postgres client programs, psql, pg_dump, etc. This also means you can work as postgres database user on remote servers.

PostgreSQL security and passwords

I'm having some issues with PostgreSQL security
I've taken the necessary steps
# ./psql -U postgres
# CREATE DATABASE devdb;
# CREATE USER devdb_user PASSWORD 'donttell';
# GRANT ALL PRIVILEGES ON DATABASE devdb TO devdb_user;
However when I try to connect to the database with
# ./psql -d devdb -U devdb_user -W
It prompts me for the password as I would expect but any password I enter will still log me in. Why is this?
Oh I see that in the pg_hba.conf it was reading the incoming connection as a local connection with had the trust authentication setting. Changed it to md5 and everything is all tightened up again

psql: FATAL: Peer authentication failed for user "dev"

when i create a new user, but it cannot login the database.
I do that like this:
postgres#Aspire:/home/XXX$ createuser dev
Shall the new role be a superuser? (y/n) n
Shall the new role be allowed to create databases? (y/n) y
Shall the new role be allowed to create more new roles? (y/n) y
then create a database:
postgres#Aspire:/home/XXX$ createdb -O dev test_development
after that, I try psql -U dev -W test_development to login, but get the error:
psql: FATAL: Peer authentication failed for user "dev"
I tried to solve the problem but failed.
Try:
psql -U user_name -h 127.0.0.1 -d db_name
where
-U is the database user name
-h is the hostname/IP of the local server, thus avoiding Unix domain sockets
-d is the database name to connect to
This is then evaluated as a "network" connection by Postgresql rather than a Unix domain socket connection, thus not evaluated as a "local" connect as you might see in pg_hba.conf:
local all all peer
Your 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 dev and then login as dev or use sudo -u dev psql test_development 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=test_development --username=dev (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.
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 if PostgreSQL is running you'll need to make it re-read the configuration by reloading (pg_ctl reload) or restarting (sudo service postgresql restart).
* The file pg_hba.conf will most likely be at /etc/postgresql/9.x/main/pg_hba.conf
Edited: Remarks from #Chloe, #JavierEH, #Jonas Eicher, #fccoelho, #Joanis, #Uphill_What comments incorporated into answer.
Peer authentication means that postgres asks the operating system for your login name and uses this for authentication. To login as user "dev" using peer authentication on postgres, you must also be the user "dev" on the operating system.
You can find details to the authentication methods in the Postgresql documentation.
Hint: If no authentication method works anymore, disconnect the server from the network and use method "trust" for "localhost" (and double check that your server is not reachable through the network while method "trust" is enabled).
When you specify:
psql -U user
it connects via UNIX Socket, which by default uses peer authentication, unless specified in pg_hba.conf otherwise.
You can specify:
host database user 127.0.0.1/32 md5
host database user ::1/128 md5
to get TCP/IP connection on loopback interface (both IPv4 and IPv6) for specified database and user.
After changes you have to restart postgres or reload it's configuration.
Restart that should work in modern RHEL/Debian based distros:
service postgresql restart
Reload should work in following way:
pg_ctl reload
but the command may differ depending of PATH configuration - you may have to specify absolute path, which may be different, depending on way the postgres was installed.
Then you can use:
psql -h localhost -U user -d database
to login with that user to specified database over TCP/IP.
md5 stands for encrypted password, while you can also specify password for plain text passwords during authorisation. These 2 options shouldn't be of a great matter as long as database server is only locally accessible, with no network access.
Important note:
Definition order in pg_hba.conf matters - rules are read from top to bottom, like iptables, so you probably want to add proposed rules above the rule:
host all all 127.0.0.1/32 ident
While #flaviodesousa's answer would work, it also makes it mandatory for all users (everyone else) to enter a password.
Sometime it makes sense to keep peer authentication for everyone else, but make an exception for a service user. In that case you would want to add a line to the pg_hba.conf that looks like:
local all some_batch_user md5
I would recommend that you add this line right below the commented header line:
# TYPE DATABASE USER ADDRESS METHOD
local all some_batch_user md5
You will need to restart PostgreSQL using
sudo service postgresql restart
If you're using 9.3, your pg_hba.conf would most likely be:
/etc/postgresql/9.3/main/pg_hba.conf
This works for me when I run into it:
sudo -u username psql
I simply had to add -h localhost
The easiest solution:
CREATE USER dev WITH PASSWORD 'dev';
CREATE DATABASE test_development;
GRANT ALL PRIVILEGES ON DATABASE test_development to dev;
ALTER ROLE dev CREATEROLE CREATEDB;
In my case I was using different port. Default is 5432. I was using 5433. This worked for me:
$ psql -f update_table.sql -d db_name -U db_user_name -h 127.0.0.1 -p 5433
For people in the future seeing this, postgres is in the /usr/lib/postgresql/10/bin on my Ubuntu server.
I added it to the PATH in my .bashrc file, and add this line at the end
PATH=$PATH:/usr/lib/postgresql/10/bin
then on the command line
$> source ./.bashrc
I refreshed my bash environment. Now I can use postgres -D /wherever from any directory
pg_dump -h localhost -U postgres -F c -b -v -f mydb.backup mydb
Try in terminal:
>> psql -U role_name -d database -h hostname.<domain>.com -W

How can I change a PostgreSQL user password?

How do I change the password for a PostgreSQL user?
To log in without a password:
sudo -u user_name psql db_name
To reset the password if you have forgotten:
ALTER USER user_name WITH PASSWORD 'new_password';
To change the PostgreSQL user's password, follow these steps:
log in into the psql console:
sudo -u postgres psql
Then in the psql console, change the password and quit:
postgres=# \password postgres
Enter new password: <new-password>
postgres=# \q
Or using a query:
ALTER USER postgres PASSWORD '<new-password>';
Or in one line
sudo -u postgres psql -c "ALTER USER postgres PASSWORD '<new-password>';"
Note:
If that does not work, reconfigure authentication by editing /etc/postgresql/9.1/main/pg_hba.conf (the path will differ) and change:
local all all peer # change this to md5
to
local all all md5 # like this
Then restart the server:
sudo service postgresql restart
You can and should have the users' password encrypted:
ALTER USER username WITH ENCRYPTED PASSWORD 'password';
I believe the best way to change the password is simply to use:
\password
in the Postgres console.
Per ALTER USER documentation:
Caution must be exercised when specifying an unencrypted password with
this command. The password will be transmitted to the server in
cleartext, and it might also be logged in the client's command history
or the server log. psql contains a command \password that can be used
to change a role's password without exposing the cleartext password.
Note: ALTER USER is an alias for ALTER ROLE
To change the password using the Linux command line, use:
sudo -u <user_name> psql -c "ALTER USER <user_name> PASSWORD '<new_password>';"
To the change password:
sudo -u postgres psql
Then
\password postgres
Now enter the new password and confirm.
Then \q to exit.
Go to your PostgreSQL configuration and edit file pg_hba.conf:
sudo vim /etc/postgresql/9.3/main/pg_hba.conf
Then change this line:
Database administrative login by Unix domain socket
local all postgres md5
to:
Database administrative login by Unix domain socket
local all postgres peer
Then restart the PostgreSQL service via the 'sudo' command. Then
psql -U postgres
You will be now entered and will see the PostgreSQL terminal.
Then enter
\password
And enter the new password for the PostgreSQL default user. After successfully changing the password again, go to the pg_hba.conf and revert the change to "md5".
Now you will be logged in as
psql -U postgres
with your new password.
Setting up a password for the postgres role
sudo -u postgres psql
You will get a prompt like the following:
postgres=#
Change password to PostgreSQL for user postgres
ALTER USER postgres WITH ENCRYPTED PASSWORD 'postgres';
You will get something as follows:
ALTER ROLE
To do this we need to edit the pg_hba.conf file.
(Feel free to replace nano with an editor of your choice.)
sudo nano /etc/postgresql/9.5/main/pg_hba.conf
Update in the pg_hba.conf file
Look for an uncommented line (a line that doesn’t start with #) that has the contents shown below. The spacing will be slightly different, but the words should be the same.
local postgres postgres peer
to
local postgres postgres md5
Now we need to restart PostgreSQL, so the changes take effect
sudo service postgresql restart
To request a new password for the postgres user (without showing it in the command):
sudo -u postgres psql -c "\password"
This was the first result on google, when I was looking how to rename a user, so:
ALTER USER <username> WITH PASSWORD '<new_password>'; -- change password
ALTER USER <old_username> RENAME TO <new_username>; -- rename user
A couple of other commands helpful for user management:
CREATE USER <username> PASSWORD '<password>' IN GROUP <group>;
DROP USER <username>;
Move user to another group
ALTER GROUP <old_group> DROP USER <username>;
ALTER GROUP <new_group> ADD USER <username>;
If you are on Windows.
Open pg_hba.conf file and change from md5 to peer.
Open cmd and type psql postgres postgres.
Then type \password to be prompted for a new password.
Refer to this Medium post for further information & granular steps.
The configuration that I've got on my server was customized a lot, and I managed to change the password only after I set trust authentication in the pg_hba.conf file:
local all all trust
Don't forget to change this back to password or md5.
For my case on Ubuntu 14.04 (Trusty Tahr), installed with PostgreSQL 10.3: I need to follow the following steps
su - postgres to switch the user to postgres
psql to enter the PostgreSQL shell
\password and then enter your password
Q to quit the shell session
Then you switch back to root by executing exit and configure your pg_hba.conf (mine is at /etc/postgresql/10/main/pg_hba.conf) by making sure you have the following line
local all postgres md5
Restart your PostgreSQL service by service postgresql restart
Now switch to the postgres user and enter the PostgreSQL shell again. It will prompt you for a password.
Use this:
\password
Enter the new password you want for that user and then confirm it.
If you don't remember the password and you want to change it, you can log in as "postgres" and then use this:
ALTER USER 'the username' WITH PASSWORD 'the new password';
TLDR:
On many systems, a user's account often contains a period, or some sort of punctuation (user: john.smith, horise.johnson). In these cases, a modification will have to be made to the accepted answer above. The change requires the username to be double-quoted.
Example
ALTER USER "username.lastname" WITH PASSWORD 'password';
Rationale:
PostgreSQL is quite picky on when to use a 'double quote' and when to use a 'single quote'. Typically, when providing a string, you would use a single quote.
This is similar to other answers in syntax, but it should be known that you can also pass the MD5 hash value of the password, so you are not transmitting a plain text password.
Here are a few scenarios of unintended consequences of altering a users password in plain text.
If you do not have SSL and are modifying remotely you are transmitting the plain text password across the network.
If you have your logging configuration set to log DDL statements log_statement = ddl or higher, then your plain text password will show up in your error logs.
If you are not protecting these logs, it’s a problem.
If you collect these logs/ETL them and display them where others have access, they could end up seeing this password, etc.
If you allow a user to manage their password, they are unknowingly revealing a password to an administrator or low-level employee tasked with reviewing logs.
With that said, here is how we can alter a user's password by building an MD5 hash value of the password.
PostgreSQL, when hashing a password as MD5, salts the password with the user name and then prepends the text "md5" to the resulting hash.
Example: "md5"+md5(password + username)
In Bash:
echo -n "passwordStringUserName" | md5sum | awk '{print "md5"$1}'
Output:
md5d6a35858d61d85e4a82ab1fb044aba9d
In PowerShell:
[PSCredential] $Credential = Get-Credential
$StringBuilder = New-Object System.Text.StringBuilder
$null = $StringBuilder.Append('md5');
[System.Security.Cryptography.HashAlgorithm]::Create('md5').ComputeHash([System.Text.Encoding]::ASCII.GetBytes(((ConvertFrom-SecureStringToPlainText -SecureString $Credential.Password) + $Credential.UserName))) | ForEach-Object {
$null = $StringBuilder.Append($_.ToString("x2"))
}
$StringBuilder.ToString();
## OUTPUT
md5d6a35858d61d85e4a82ab1fb044aba9d
So finally our ALTER USER command will look like
ALTER USER UserName WITH PASSWORD 'md5d6a35858d61d85e4a82ab1fb044aba9d';
Relevant links (note I will only link to the latest versions of the documentation. For older, it changes some, but MD5 is still supported a ways back.)
create role
The password is always stored encrypted in the system catalogs. The ENCRYPTED keyword has no effect, but is accepted for backwards compatibility. The method of encryption is determined by the configuration parameter password_encryption. If the presented password string is already in MD5-encrypted or SCRAM-encrypted format, then it is stored as-is regardless of password_encryption (since the system cannot decrypt the specified encrypted password string, to encrypt it in a different format). This allows reloading of encrypted passwords during dump/restore.
Configuration setting for password_encryption
PostgreSQL password authentication documentation
Building PostgreSQL password MD5 hash value
And the fully automated way with Bash and expect (in this example we provision a new PostgreSQL administrator with the newly provisioned PostgreSQL password both on OS and PostgreSQL run-time level):
# The $postgres_usr_pw and the other Bash variables MUST be defined
# for reference the manual way of doing things automated with expect bellow
#echo "copy-paste: $postgres_usr_pw"
#sudo -u postgres psql -c "\password"
# The OS password could / should be different
sudo -u root echo "postgres:$postgres_usr_pw" | sudo chpasswd
expect <<- EOF_EXPECT
set timeout -1
spawn sudo -u postgres psql -c "\\\password"
expect "Enter new password: "
send -- "$postgres_usr_pw\r"
expect "Enter it again: "
send -- "$postgres_usr_pw\r"
expect eof
EOF_EXPECT
cd /tmp/
# At this point the 'postgres' executable uses the new password
sudo -u postgres PGPASSWORD=$postgres_usr_pw psql \
--port $postgres_db_port --host $postgres_db_host -c "
DO \$\$DECLARE r record;
BEGIN
IF NOT EXISTS (
SELECT
FROM pg_catalog.pg_roles
WHERE rolname = '"$postgres_db_useradmin"') THEN
CREATE ROLE "$postgres_db_useradmin" WITH SUPERUSER CREATEROLE
CREATEDB REPLICATION BYPASSRLS
PASSWORD '"$postgres_db_useradmin_pw"' LOGIN ;
END IF;
END\$\$;
ALTER ROLE "$postgres_db_useradmin" WITH SUPERUSER CREATEROLE
CREATEDB REPLICATION BYPASSRLS
PASSWORD '"$postgres_db_useradmin_pw"' LOGIN ;
"
Change password to "postgres" for user "postgres":
# ALTER USER postgres WITH ENCRYPTED PASSWORD '<NEW-PASSWORD>';
I was on Windows (Windows Server 2019; PostgreSQL 10), so local type connections (pg_hba.conf: local all all peer) are not supported.
The following should work on Windows and Unix systems alike:
backup pg_hba.conf to pg_hba.orig.conf e.g.
create pg_hba.conf with only this: host all all 127.0.0.1/32 trust
restart pg (service)
execute psql -U postgres -h 127.0.0.1
enter (in pgctl console) alter user postgres with password 'SomePass';
restore pg_hba.conf from 1. above
Check file pg_hba.conf.
In case the authentication method is 'peer', the client's operating system user name/password must match the database user name and password. In that case, set the password for Linux user 'postgres' and the DB user 'postgres' to be the same.
See the documentation for details: 19.1. The pg_hba.conf File
In general, just use the pgAdmin UI for doing database-related activity.
If instead you are focusing more in automating database setup for your local development, CI, etc.
For example, you can use a simple combination like this.
(a) Create a dummy super user via Jenkins with a command similar to this:
docker exec -t postgres11-instance1 createuser --username=postgres --superuser experiment001
This will create a super user called experiment001 in you PostgreSQL database.
(b) Give this user some password by running a NON-Interactive SQL command.
docker exec -t postgres11-instance1 psql -U experiment001 -d postgres -c "ALTER USER experiment001 WITH PASSWORD 'experiment001' "
PostgreSQL is probably the best database out there for command line (non-interactive) tooling. Creating users, running SQL, making backup of database, etc.
In general, it is all quite basic with PostgreSQL, and it is overall quite trivial to integrate this into your development setup scripts or into automated CI configuration.
Using pgAdmin 4:
Menu Object → Change password...
Most of the answers were mostly correct, but you need to look out for minor things. The problem I had was that I didn't ever set the password of "postgres", so I couldn't log into an SQL command line that allowed me to change passwords. These are the steps that I used successfully (note that most or all commands need sudo or root user):
Edit the pg_hba.conf file in the data directory of the DB cluster you're trying to connect to.
The folder of the data directory can be found by inspecting the systemd command line, easily obtained with systemctl status postgresql#VERSION-DB_CLUSTER. Replace VERSION with your psql version and DB_CLUSTER with the name of your database cluster. This may be main if it was automatically created, so, e.g., postgresql#13-main. Alternatively, my Bash shell provided auto-complete after entering postgresql#, so you could try that or look for the PostgreSQL services in the list of all services (systemctl -a). Once you have the status output, look for the second command line after CGroup, which should be rather long, and start with /usr/lib/postgresql/13/bin/postgres or similar (depending on version, distro, and installation method). You are looking for the directory after -D, for example /var/lib/postgresql/13/main.
Add the following line: host all all 127.0.0.1/32 trust. This allows for all users on all databases to connect to the database via IPv4 on the local machine unconditionally, without asking for a password.
This is a temporary fix and don't forget to remove this line again later on. Just to be sure, I commented out the host all all 127.0.0.1/32 md5 (md5 may be replaced by scram-sha-256), which is valid for the same login data, just requiring a password.
Restart the database service: systemctl restart postgresql#... Again, use the exact service you found earlier.
Check that the service started properly with systemctl status postgresql#....
Connect with psql, and very importantly, force psql to not ask for a password. In my experience, it will ask you for a password even though the server doesn't care, and will still reject your login if your password was wrong. This can be accomplished with the -w flag.
The full command line looks something like this: sudo -u postgres psql -w -h 127.0.0.1 -p 5432. Here, postgres is your user and you may have changed that. 5432 is the port of the cluster-specific server and may be higher if you are running more than one cluster (I have 5434 for example).
Change the password with the \password special command.
Remember to remove the password ignore workaround and restart the server to apply the configuration.