Authenticating Apache users against OwnCloud/NextCloud users' table

Apache module mod_authn_dbd offers a convenient way to use the OwnCloud/NextCloud users' table as backend for basic HTTP authentication in another context (e.g. a private website next to your OwnCloud/NextCloud site on the same server).

What follows assumes that you are using Debian or Ubuntu and MySQL/MariaDB. Otherwise PostgreSQL and SQLite3 DBD drivers are available as well, adapt the recipe accordingly.

  • Install package libaprutil1-dbd-mysql (this provides the MySQL DBD driver)
  • Take note of the user and password used by OwnCloud/NextCloud to access its database. They are written in OwnCloud/NextCloud's config.php:
    'dbuser' => 'oc_admin',
    'dbpassword' => 'pX65Ty5DrHQkYPE5HRsDvyFHlZZHcm',
  • Edit your site configuration file (e.g. /etc/apache2/sites-available/mysite.conf):
    # DBD configuration
    DBDriver mysql
    DBDParams "dbname=nextcloud user=oc_admin pass=pX65Ty5DrHQkYPE5HRsDvyFHlZZHcm"
    DBDMin 4
    DBDKeep 8
    DBDMax 20
    DBDExptime 300
    # Protected path
    <Directory ~ /var/www/mysite/private>
        AuthType Basic
        AuthName "My site"
        AuthBasicProvider socache dbd
        AuthnCacheProvideFor dbd
        AuthnCacheContext my-site
        AuthDBDUserPWQuery "SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(password, '|', 2), '|', -1) from oc_users where uid = %s"
    </Directory>
  • Enable the required Apache modules:
    sudo a2enmod dbd
    sudo a2enmod authn_dbd
    sudo a2enmod authn_socache
  • Restart Apache:
    sudo systemctl restart apache2

Notes:

  • The key directive is AuthDBDUserPWQuery, which defines the query that extracts the password from the OwnCloud/NextCloud users' table. The current stable version of NextCloud (13) stores passwords as prefixed hashes (hence the nested SUBSTRING_INDEX stuff) using the PHP function password_hash with the default bcrypt algorithm (see library Security/Hasher.php). The important point here is that bcrypt is one of the encryption formats understood by Apache. Now its perfectly possible that your version of OwnCloud/NextCloud implements another type of encryption, supported by Apache or not. Have a look at the password values in the users' table. If they begin with the prefix "1|" followed by $2y$, the second part is a bcrypt hash.