How do I connect to a local postgres database without password from a script within Apache
up vote 0 down vote favorite
I have a Python script that should load some data into postgres when a POST request is sent to Apache Webserver. In the script a system user (dbuser) is used to connect to the database (which works fine with psql). The script however cannot connect when it is executed within Apache, returning the following error:
Peer authentication failed for user dbuser
Is there a way to allow the script to connect without providing it the user password?
python apache postgresql cgi
shareimprove this question
asked Jun 4 '15 at 9:48
add a comment
active oldest votes
up vote 1 down vote
The solution I've found uses ident authentication with user maps.
The first thing to notice is that, although an username is provided in the script, when connecting via Apache, that user is used for peer authentication (which fails, requiring a password). However, the system user requesting access to postgresql is the one running Apache (namely www-data), thus enabling us to configure an user map, allowing is to authenticate to the server as another system user (thus leveraging ident authentication). Here follows the configuration files content:
In pg_ident.conf we configure the user map:
# MAPNAME SYSTEM-USERNAME PG-USERNAME
web www-data dbuser
web dbuser dbuser
In pg_hba.conf we add the map as an option to the local peer authentication:
# "local" is for Unix domain socket connections only
# TYPE DATABASE USER ADDRESS METHOD
local all all peer map=web
After reloading the server, the script can access the database as if it was executed directly the the user "dbuser", without the need for a password.
shareimprove this answer