DEV Community

Nhat Bui
Nhat Bui

Posted on

Creating a Role in Postgres Properly

Here's how to create a role that can log in, but don't give it a password:

CREATE ROLE nhatbui LOGIN;
Enter fullscreen mode Exit fullscreen mode

And here is creating a role with a password that is valid until the end of 2022. After one second has ticked in 2023, the password is no longer valid:

CREATE USER nhatbui WITH PASSWORD 'st@bl3nhAt' VALID UNTIL '2023-01-01';
Enter fullscreen mode Exit fullscreen mode

The syntax is fine. But what could possibly go wrong? Oh dear, your password will appear as plain text somewhere in the log file; it can be stolen in no easier way. To do it properly, we first create a role that can log in but don't give it a password:

CREATE ROLE nhatbui LOGIN;
Enter fullscreen mode Exit fullscreen mode

Once the role nhatbui is created, we can then give it a password with this command (psql):

\password nhatbui
Enter fullscreen mode Exit fullscreen mode

The terminal now will ask you to type in the new password. Just like other passwords, it will be hidden in the terminal. So just type without wondering. Here's what mine displays:

postgres=# \password nhatbui
Enter new password for user "nhatbui": 
Enter it again:
Enter fullscreen mode Exit fullscreen mode

As far as I am aware, Postgres will hash the password before storing it, unless the supplied string is already hashed. So you don't have to hash it manually.

Top comments (0)