machineghost
machineghost

Reputation: 35790

Why Is Knex.js Failing on Password Authentication When My Database Has No Password?

I'm trying to connect to my database using Knex like so:

const client = knex({
  client: 'postgresql',
  connection: {
    host: '127.0.0.1',
    user: 'me',
    database: 'my_db'
  }
});
client('some_table').then(console.log);

When I created the database (using createdb my_db at the command line) I set no password. At the command line I can run psql -d my_db and it works just fine.

However, when I try to use Knex, I get an error:

Unhandled rejection error: password authentication failed for user "me"

This happens whether I set a null password, an empty string ('') password, or leave the field off of the configuration entirely.

Can anyone explain why Knex insists on failing password authentication ... when there is no password (and when I can connect without one at the command line just fine)?

Upvotes: 0

Views: 1267

Answers (1)

richyen
richyen

Reputation: 9978

PostgreSQL does not permit login based on the presence/absence of a password. Rather, all login authentication is handled via pg_hba.conf. In your particular case--creating the me user without a password (or using null or '', as you would describe it)--the absence of the password doesn't necessarily allow your user to log in. In fact, setting no password will not allow that user to log in unless pg_hba.conf was set to some password-less setting (i.e., peer or trust).

If you want password-less login for the me user (I assume for testing/development purposes, as having password-less login is not good security practice in production), you could simply set trust-level authentication in pg_hba.conf:

#conn_origin  database  user  ip_mask   auth_method
host          all       me    0.0.0.0/0 trust

The more secure method of implementing password-less authentication would be to use a .pgpass file or set the PGPASSWORD environment variable. Seeing that you are trying to use knex.js, you may be better off with tweaking pg_hba.conf as above. Again, I don't know what your intentions are, but please be safe out there ;)

Disclosure: I work for EnterpriseDB (EDB)

Upvotes: 1

Related Questions