MySQL Authentication on Nginx

If you are like me then one of your biggest pet peeve’s with Nginx is its lack of authentication methods like those so easily accessible in Apache. Beyond that, if you would like to add an authentication method to Nginx, it will typically require a recompile. If you are running Debian or Ubuntu then I would like to introduce you to nginx-extras. The package nginx-extras is compiled with all the standard modules as well as some very useful extras which are listed here.  If you are running Debian, than you may want to check out my previous article on how to install the Nginx Latest on Debian Wheezy. I have to say that I searched Google high and low looking for a good solution, then it dawned on me that the framework for MySQL Authentication was already in place on the server I was configuring. The idea came to me right after setting up Postfix SMTP Authentication for virtual users using libpam-mysql.  I had previously stumbled upon Nginx PAM Authentication here, so I wondered why not use libpam-mysql. So without further ado, first we will have to ensure that we have the required packages which are nginx-extras and libpam-mysql.

apt-get install nginx-extras libpam-mysql

Once the required packages are installed we can start configuring our virtual host. Configuring Nginx to Authenticate using PAM is as simple as adding the following two statements to your Nginx virtual host.

auth_pam "Restricted Zone";
auth_pam_service_name "nginx-vhostname";

Note that nginx-vhostname will be created at /etc/pam.d/nginx-vhostname and will be used to define your connection to your MySQL or MariaDB Database. Below are the contents of the file. In this example I am using MySQL Authentication for DSPAM so of course you will need to adjust the file to meet your own needs.

auth required user=db_user passwd=db_pass host= db=mail table=users usercolumn=email passwdcolumn=password crypt=1
account sufficient user=db_user passwd=db_pass host= db=mail table=users usercolumn=email passwdcolumn=password crypt=1

That is it. Lastly you will want to restart Nginx and then navigate to your website and you will now be prompted to enter a username and password.

Warning: Version 10.0.9 and 5.5.36 of MariaDB Server will break libpam-mysql. Please refer to this MariaDB Development ticket for further information. The most recent versions are working as expected.
If you are looking for other authentication methods using nginx, please see our companion articles AD/LDAP Authentication on Nginx and Certificate Authentication on Nginx

Did you find this article useful? Why not share it with your friends?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.