privacyIDEA: How to Secure Windows and Active Directory with Open Source MFA
In this tutorial, we will install and configure an MFA server using privacyIDEA on Linux. The goal will be to log in to a Windows workstation joined to Active Directory using a username and password, while adding a second authentication factor.
privacyIDEA is a free and open source Python application that lets you implement an on-prem MFA server to improve access security with multiple authentication tokens.

As a reminder, MFA, also called "multi-factor authentication", is designed to require one or more authentication factors in addition to a first authentication factor, such as a username and password, to prove a user’s identity.
It is an essential security measure these days and is probably part of your everyday life: social networks, online banking, and even delivery platforms use these systems to prevent accounts from being compromised due to a data breach, for example. Most companies today integrate at least one MFA mechanism into a login flow, whether at sign-in, during VPN access, or for critical services.
The solution presented today, privacyIDEA, offers a wide range of available authentication tokens:
- TOTP: temporary code generated by an app such as privacyIDEA Authenticator, Google Authenticator, or FreeOTP.
- HOTP: one-time code based on a counter.
- Push: notification sent to the phone that the user approves.
- SMS: one-time code sent by text message.
- E-mail: code sent to the user’s email address.
- Passkey / FIDO2 / WebAuthn: authentication using a cryptographic key, optionally protected locally by a fingerprint, face recognition, or a PIN.
- YubiKey, Nitrokey, VASCO, and other hardware tokens.
- X.509 certificate: possession of a certificate and its private key.
- TiQR: authentication using a mobile app and a QR code.
- TAN or paper codes: list of one-time codes.
- And many more, available in the official documentation.
The project is currently maintained by the German company NetKnights GmbH, which also provides professional support for the solution. The official documentation is available on the privacyidea.org website.

Here is the lab that will be deployed for this tutorial:
- A Rocky Linux 10.2 VM to host the privacyIDEA application and its database.
- A Windows Server 2022 VM acting as the Active Directory domain controller.
- A Windows 11 client VM to test MFA through the privacyIDEA Credential Provider.
Prerequisites
A number of prerequisites are required to install privacyIDEA version 3.14, the latest stable release at the time of writing.
First of all, privacyIDEA can be installed on any Linux distribution using a Python virtual environment. There are also official packages for the following Ubuntu versions: 22.04 LTS, 24.04 LTS, and 26.04 LTS, and a deployment via Docker is possible. However, the privacyIDEA server cannot be installed on Windows or macOS.
To make this tutorial useful to as many people as possible, I will install the application using a Python virtual environment.
A Python virtual environment is an isolated folder that contains its own logical Python installation and, more importantly, its own libraries. It helps prevent the dependencies of multiple projects from mixing together.
Here are the prerequisites:
- Compatible Python versions range from 3.11 to 3.15. Other versions are not officially tested.
- privacyIDEA requires a Python virtual environment through the venv module.
- The application relies on a relational database to store all of its data. Since privacyIDEA is a Python application, it uses the SQLAlchemy utility to communicate with the database. The documentation states that the best results were obtained with a MySQL database. However, it also states that databases supported by SQLAlchemy should work. In my case, I will follow the vendor’s documentation and install a MySQL database. You can also review the list of supported databases and versions here.
- A WSGI-compatible web server must be installed. WSGI stands for “Web Server Gateway Interface”; it is a standard that allows a web server to communicate with a Python application. I will use Apache with the “
mod_wsgi” module. - The vendor strongly recommends having working DNS resolution and avoiding static IP addresses when declaring the names of your services (for example, a domain controller). It also emphasizes that time must be correctly synchronized, especially for TOTP tokens, which are time-based.
As for sizing the server and its database, I could not find any concrete recommendation from the vendor. You will therefore need to analyze the load and adjust the allocated resources accordingly. The vendor still provides guidance for diagnosing performance issues on this page, so do not hesitate to use it if you experience slowness.
Let’s move on to installation.
Installing privacyIDEA
Installing dependencies
Now that we have reviewed the prerequisites, it is time to proceed with the installation. I personally use a Rocky Linux distribution, which belongs to the Red Hat family. You will need to adapt the commands below to your distribution.
Before installing the dependencies required by privacyIDEA, it is recommended to update the packages available from the repositories. This ensures that packages are up to date, improves security, and helps avoid dependency conflicts.
sudo dnf update -yOn most modern distributions, a version of Python is already preinstalled. You can check whether Python is installed with the following command:
python3 --versionRocky Linux 10 does not provide mysql packages by default, so I added the official repository and its GPG key with the command below. You may need to do the same depending on the DBMS you want to install and your distribution.
sudo dnf install -y https://dev.mysql.com/get/mysql84-community-release-el10-3.noarch.rpmWe can now install the dependencies required by privacyIDEA, namely: Python, a MySQL database, an Apache web server, the wsgi module, the SSL module, and tools for SELinux administration (specific to my distribution). If the installed Python version is within the supported range, then you can remove the "python3.x" package.
sudo dnf install python3.12 mysql-community-server httpd python3-mod_wsgi mod_ssl policycoreutils-python-utils -yCreating the service account and directories
privacyIDEA will rely on a user and on directories that we will create to allow the application to function properly.
First, create the user "privacyIDEA". The account will have the following options:
- system: marks the account as a system account. It will have a UID and GID reserved for system accounts.
- home-dir /opt/privacyidea: this is the user’s home directory.
- create-home: this option automatically creates the user’s home directory. The
/opt/privacyideadirectory will be created automatically. - shell /sbin/nologin: the account cannot be used for SSH access or through
su - privacyidea.
/opt is a directory present on Linux and Unix, defined by the Filesystem Hierarchy Standard (FHS). It is generally used by self-contained third-party applications that were not installed through a package manager.
sudo useradd --system --home-dir /opt/privacyidea --create-home --shell /sbin/nologin privacyideaWe will create the /etc/privacyidea directory as well as the pi.cfg file, which will host the application’s configuration. Since this directory and file are sensitive, we will protect them with read/write permissions. The /var/log/privacyidea directory and its privacyidea.log file will store the application logs.
sudo mkdir /etc/privacyidea /var/log/privacyideqsudo touch /etc/privacyidea/pi.cfg /var/log/privacyidea/privacyidea.logsudo chmod 750 /etc/privacyidea/
sudo chmod 640 /etc/privacyidea/pi.cfgAssign permissions to the privacyidea user and group on these directories and their entire contents using the -R option (recursive).
sudo chown -R privacyidea:privacyidea /etc/privacyidea /var/log/privacyidea/Database configuration
Now that the directories are created, we will prepare the MySQL database to host the application data. Start the mysqld service with the following systemctl command.
sudo systemctl enable --now mysqldCheck that the service is active.
systemctl status mysqld
In the installed MySQL version, a temporary password is generated in the /var/log/mysqld.log file for use by the DBMS root account. I used the command below to retrieve it:
sudo grep 'temporary password' /var/log/mysqld.log
MySQL provides the mysql_secure_installation utility to secure the installation. Run it with the command below:
mysql_secure_installationWe will run the utility twice. During the first run, you will need to change the DBMS root password by providing the retrieved temporary password.

For the second run, you will be prompted to change the root password, but also to remove anonymous users, disable remote root access, and so on. Everything is clearly explained. Here is an example on my server to guide you.

The first thing we will configure is the MySQL database by adding a database and a user with rights on that database.
Connect to your database as root and enter the DBMS root password (the one defined when running mysql_secure_installation):
mysql -u root -pOnce inside the MySQL shell, enter the commands below to create the pi database, the pi@localhost user, and grant it the necessary permissions on the database.
CREATE DATABASE pi;
CREATE USER "pi"@"localhost" IDENTIFIED BY "motdepasse";
GRANT ALL PRIVILEGES ON pi.* TO "pi"@"localhost";
exit;The result of these three commands should return "Query OK", as shown in the screenshot below.

SQLAlchemy configuration
Now that the pi instance is created, we will tell privacyIDEA how to connect to the database in the /etc/privacyidea/pi.cfg configuration file. I took the template from the official documentation and commented it to help you understand the parameters.
sudo nano /etc/privacyidea/pi.cfg
# ============================================================
# Active configuration
# ============================================================
# Realms allowed to contain privacyIDEA administrators
SUPERUSER_REALM = ['super', 'administrators']
# Database connection URI.
SQLALCHEMY_DATABASE_URI = 'sqlite:////etc/privacyidea/data.sqlite'
# Encryption key for sensitive token data
PI_ENCFILE = '/etc/privacyidea/enckey'
# Audit log signing keys
PI_AUDIT_KEY_PRIVATE = '/etc/privacyidea/private.pem'
PI_AUDIT_KEY_PUBLIC = '/etc/privacyidea/public.pem'
# Log file
PI_LOGFILE = '/var/log/privacyidea/privacyidea.log'
# Log level: (10 = DEBUG | 20 = INFO | 30 = WARNING | 40 = ERROR | 50 = CRITICAL)
PI_LOGLEVEL = 20
# Public URL of the privacyIDEA server. Used for password recovery links (only when the directory is writable)
PI_BASE_URL = "https://privacyidea.it-connect.local"
# Enable Content Security Policy to improve security
PI_ENABLE_CSP = True
# Force HTTPS usage
PI_FORCE_HTTPS = True
# ============================================================
# Available / disabled options
# ============================================================
# Interface languages, in order of preference
#PI_PREFERRED_LANGUAGE = ["en"]
# Advanced SQLAlchemy options
# SQLALCHEMY_ENGINE_OPTIONS = {"max_identifier_length": 128}
# Custom audit module
# PI_AUDIT_MODULE = <python audit module>
# Separate database for audit
# PI_AUDIT_SQL_URI = <special audit log DB uri>
# Specific SQL options for the audit database
# PI_AUDIT_SQL_OPTIONS = {}
# Python function executed during initialization
# PI_INIT_CHECK_HOOK = 'your.module.function'
# Completely disable the Web UI
# PI_UI_DEACTIVATED = TrueThe parameter that interests us here is "SQLALCHEMY_DATABASE_URI". Here is the modification we will apply to this parameter:
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://pi:MOT_DE_PASSE@localhost/pi'
Let’s break down this URL to better understand it:
mysql+pymysqlmeans that the MySQL database engine is used along with thepymsqldriver to communicate with the database.- The two slashes introduce the credentials. Only SQLite uses three slashes, because it does not have a server to contact.
pi:MOT_DE_PASSEspecifies the username and password to use to connect to the database.@localhost/piindicates that we are using the previously createdpidatabase on the local host.
This URL can change depending on the DBMS used. You can find configuration examples on the official SQLAlchemy website.
Web server and WSGI configuration
To start the application, Apache will use a WSGI script provided by privacyIDEA. The documentation states that it is possible to run multiple privacyIDEA instances. For more details on setting up a multi-instance configuration, click here.
The script is not yet present on the machine; however, it will be present after privacyIDEA is installed. Enable Apache to start at boot.
sudo systemctl enable httpdCreate the privacyidea.conf file containing the WSGI script Apache must execute, as well as the parameters to apply. As for the certificate and key that Apache will use for the HTTPS connection, they will be generated in the next step.
sudo nano /etc/httpd/conf.d/privacyidea.conf
# Apache listening port
Listen 443 https
# Reduce information exposed by Apache
ServerTokens Prod
ServerSignature Off
TraceEnable off
# VirtualHost and listening port
<VirtualHost _default_:443>
# Server DNS name
ServerName privacyidea.it-connect.local
# privacyIDEA WSGI application
WSGIScriptAlias / /etc/privacyidea/privacyideaapp.wsgi
# Deny access to system files by default
<Directory />
Require all denied
</Directory>
# Allow only the privacyIDEA WSGI script
<Directory /etc/privacyidea>
<Files privacyideaapp.wsgi>
Require all granted
</Files>
</Directory>
# Dedicated WSGI process and privacyIDEA Python virtual environment
WSGIDaemonProcess privacyidea \
processes=1 \
threads=15 \
display-name=%{GROUP} \
user=privacyidea \
group=privacyidea \
python-home=/opt/privacyidea
# Use the privacyIDEA process
WSGIProcessGroup privacyidea
# Python compatibility with WSGI
WSGIApplicationGroup %{GLOBAL}
# Pass the Authorization header
WSGIPassAuthorization On
# Apache logs
ErrorLog /var/log/httpd/privacyidea_error.log
CustomLog /var/log/httpd/privacyidea_access.log combined
LogLevel warn
# Enable HTTPS
SSLEngine on
# TLS certificate
SSLCertificateFile /etc/pki/tls/certs/privacyidea.crt
SSLCertificateKeyFile /etc/pki/tls/private/privacyidea.key
</VirtualHost>The httpd service may fail to start because of a missing certificate declared in the ssl.conf configuration file. This is a generic file generated by the SSL module. Rename it with the mv command. Do the same for Apache’s default welcome page.
sudo mv /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.disabled
sudo mv /etc/httpd/conf.d/welcome.conf /etc/httpd/conf.d/welcome.conf.disabledCheck that the modules are loaded properly with the following command:
httpd -M | grep -E 'wsgi|ssl'
We will generate the certificate and key to enable HTTPS using OpenSSL. In my case this is a self-signed certificate; ideally, it should still be generated with a trusted certification authority (external or internal depending on the use case).
Install the OpenSSL package:
sudo dnf install openssl -yThen generate the RSA private key and certificate using the command below. The options used are:
-x509: creates a self-signed certificate directly, without using a certificate authority.-newkey rsa:4096: creates a new 4096-bit RSA private key.-sha256: uses SHA-256 to sign the certificate.-noenc: leaves the private key without a password so Apache can start without intervention.-keyout: indicates where to write the private key. Here, it is/etc/pki/tls/private/privacyidea.key.-out: indicates where to write the certificate. In our case,/etc/pki/tls/certs/privacyidea.crt.-days 365: makes the certificate valid for 365 days.-subj: sets the common name, hereprivacyidea.it-connect.local. You can use your server’s FQDN.subjectAltName=DNS:...: adds the DNS name that clients must verify. This is essential for name validation. Make sure to change this field to match your server’s FQDN.extendedKeyUsage=serverAuth: indicates that the certificate is intended for TLS server authentication.
sudo openssl req -x509 -newkey rsa:4096 -sha256 -noenc \
-keyout /etc/pki/tls/private/privacyidea.key \
-out /etc/pki/tls/certs/privacyidea.crt \
-days 365 \
-subj "/CN=privacyidea.it-connect.local" \
-addext "subjectAltName=DNS:privacyidea.it-connect.local" \
-addext "extendedKeyUsage=serverAuth"Before starting the service, we will proceed with installing and securing privacyIDEA.
Installing privacyIDEA
Before downloading the application, declare the /opt/privacyidea directory as a Python virtual environment. However, since it is the privacyidea user that has permissions on the directory but we cannot log in through a shell with that account, we will open bash under the identity of the privacyidea user. The -H option uses the privacyidea home directory.
sudo -u privacyidea -H bashThen declare /opt/privacyidea as a Python virtual environment using the Python venv module.
python3 -m venv /opt/privacyidea/From now on, all Python commands will point to the isolated environment and will not affect the system as a whole.
Move into the directory and activate the Python virtual environment with the activate binary.
cd /opt/privacyidea
source bin/activateYou will notice that the terminal changes, since it is prefixed with "(privacyidea)":

To install all the Python dependencies required by privacyidea 3.14, the vendor provides a text file hosted on GitHub.
By retrieving it with the Python package manager pip, along with the -r option to read a file listing the dependencies, and the URL, all dependencies and compatible versions will be installed automatically.
pip install -r https://raw.githubusercontent.com/privacyidea/privacyidea/v3.14/requirements.txtYou should see all packages being installed gradually until you get the following result:

It is now time to install the application with the pip package manager. Here we will use version 3.14.
pip install privacyidea==3.14As usual, a message should appear to inform you that the installation succeeded:

Hardening
We will now secure the application and the stored data using cryptographic secrets. In the pi.cfg file, two variables contain cryptographic secrets:
PI_PEPPERis a secret used to protect administrator passwords. It also protects reset codes and API key secrets.SECRET_KEYis used to sign the authentication JWT returned by/authafter a successful authentication.
We will generate a random string for both variables using the translate command and add them to the file.
PEPPER="$(tr -dc A-Za-z0-9_ </dev/urandom | head -c24)"
echo "PI_PEPPER = '$PEPPER'" | tee -a /etc/privacyidea/pi.cfg > /dev/null
SECRET="$(tr -dc A-Za-z0-9_ </dev/urandom | head -c24)"
echo "SECRET_KEY = '$SECRET'" | tee -a /etc/privacyidea/pi.cfg > /dev/nullThe command output should add both variables followed by a random string at the end of the pi.cfg file.

All that remains is to secure the data stored in the database and sign the audit logs with the following two commands:
pi-manage setup create_enckey
pi-manage setup create_audit_keysThe first creates an encryption key in /etc/privacyidea/ used to protect sensitive data stored in the database, including certain token-related data and passwords.
The second creates a pair of RSA private and public keys to sign each entry with the private key and later verify the signature with the public key. The main goal is therefore to detect if someone modified a log entry afterward.
A warning about user permissions will appear for both commands. Do not worry, the necessary steps have already been completed previously and only the service account has rights to view the contents.

Finishing the installation
Let’s finish setting up the solution by creating the tables in the SQL database using the provided script:
pi-manage setup create_tablesThen create a local admin account with the following command, providing a password in the interactive shell.
pi-manage admin add IDENTIFIANTThe result of the first command should show the URL used, and the second should show that the administrator account was created successfully.

The script provided by privacyIDEA is required to run the application. We will create it in the same location as the one declared in the Apache configuration file. The script content is provided in the official documentation.
nano /etc/privacyidea/privacyideaapp.wsgi
import sys
sys.stdout = sys.stderr
from privacyidea.app import create_app
# Now we can select the config file:
application = create_app(config_name="production", config_file="/etc/privacyidea/pi.cfg")Close the privacyIDEA user shell with the following command:
exit
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reloadAlso remember to open port 443 on the machine’s firewall so your clients can access the site:
Add the Apache user to the privacyidea group and change permissions to add read and execute rights for the group on the /opt/privacyidea directory.
sudo usermod -aG privacyidea apache
sudo chmod 750 /opt/privacyideaSome database data is no longer useful and may eventually fill up storage. The documentation strongly recommends setting up purge jobs using cron. They are, however, included in a Docker-based installation or the Ubuntu packages.
Create the /etc/cron.d/privacyidea file.
sudo nano /etc/cron.d/privacyideaAdd the following content:
*/5 * * * * privacyidea /opt/privacyidea/bin/privacyidea-cron run_scheduled -c
0 1 * * * privacyidea /opt/privacyidea/bin/pi-manage config challenge cleanup > /dev/null
10 1 * * * privacyidea /opt/privacyidea/bin/pi-manage config remembered_device cleanup > /dev/null
20 1 * * * privacyidea /opt/privacyidea/bin/pi-manage config authcache cleanup > /dev/null
30 1 * * * privacyidea /opt/privacyidea/bin/pi-manage config metrics cleanup > /dev/null
40 1 * * * privacyidea /opt/privacyidea/bin/pi-manage conditionalaccess purge-expired-blocks > /dev/null
40 1 * * * privacyidea /opt/privacyidea/bin/pi-manage conditionalaccess purge-expired-locks > /dev/null
50 1 * * * privacyidea /opt/privacyidea/bin/privacyidea-usercache-cleanup > /dev/nullThe final step is to configure SELinux if it is active. As a reminder, SELinux is a security mechanism generally enabled by default on distributions from the Red Hat family. Its main purpose is to restrict the actions an application can perform based on defined security policies.
- The first command declares that the
/var/log/privacyideadirectory contains log files that Apache may use. - The second applies the SELinux context defined to the directory and its contents.
- Finally, the third allows Apache to establish network connections to a database and an LDAP directory.
sudo semanage fcontext -a -t httpd_sys_rw_content_t "/var/log/privacyidea(/.*)?"
sudo restorecon -Rv /var/log/privacyidea
sudo setsebool -P httpd_can_network_connect_db=on httpd_can_connect_ldap=onIf you plan to send emails, add:
sudo setsebool -P httpd_can_sendmail=onAnd for connections to remote services (HTTP, SMS gateways, PUSH tokens, RADIUS servers, Keycloak, Entra ID...), add:
sudo setsebool -P httpd_can_network_connect=on
Check the file syntax and start Apache with the following commands:
sudo apachectl configtest # Must display "Syntax OK"
sudo systemctl start httpdNormally, access to the website should work via the URL: https://host_or_IP

If your privacyIDEA page does not look like mine and seems to have no CSS style loaded, disable the PI_ENABLE_CSP setting by commenting it out or setting it to "False" in
/etc/privacyidea/pi.cfg. At the time of writing, this very useful security mechanism (especially against XSS vulnerabilities) does not seem to be compatible with the latest version. Remember to re-enable it once the issue is fixed. The HTTPS redirect enforced by PI_FORCE_HTTPS is also disabled, because it requires CSP to be active.I opened an issue on the project’s GitHub to fix this problem.
Configuration
Exploring the dashboard
Log in with the account created using the pi-manage admin add IDENTIFIANT command. Skip the welcome message about the values of Open Source and decline realm creation for now.
If the login succeeds, you should have access to the dashboard.

Let’s briefly describe the available tabs.
- The
Dashboardtab provides an overview of the solution and its activity: authentication, tokens, resolver response times... - The
Tokenstab lets you manage token enrollment, activation, deactivation, synchronization, and assignment of authentication tokens to users. It is also possible to create "Containers", logical objects used to group multiple tokens under one banner. - The
Userstab is related to user management in privacyIDEA. - The
Policiestab lets you create policies to control the application’s behavior based on different parameters. You can also add API clients for integration with external solutions such as NextCloud, AD FS, etc., and event handlers to automate actions based on events. - The
Subscriptiontab lets you import a subscription file for privacyIDEA professional support. - The
Audittab contains all event logs and all actions performed in the application. It also includes blocked IPs and users, as well as authentication logs. - The
External Servicestab is used to declare external services that can be used with privacyIDEA: SMTP server, RADIUS, certificate authority, SMS gateway, other privacyIDEA servers... - The
Configtab is used to configure the solution: the system, tokens, machine resolvers, and machines, as well as periodic tasks.
Setting up Active Directory resolvers
A resolver allows privacyIDEA to know where to search for the users and machines it must authenticate. There are two types of resolvers:
- The first resolver is the "Machine resolver", which can retrieve machines either from a local file (
/etc/hostsfor example) or from an LDAP directory such as Active Directory or OpenLDAP. - The second resolver is the "User resolver", which retrieves users from several data sources: a local file such as
/etc/passwd, an LDAP directory, an SQL database, a SCIM connector, or an HTTP server.
The "User" resolver is the one that matters for this tutorial. Go to "Users" > "Resolvers" and click on "New resolver" to add an LDAP resolver.

Then fill in the following information:
- Sections "Create User Source" and "Connection Details" :
- Resolver Name: I chose the name of the domain controller, namely "dc01.it-connect.local". You can use whatever name you want.
- Type: Choose "LDAP"
- Scope : Search scopes determine how deep a query explores the directory starting from the base DN. There are three possible options: Base (only the specified object), LEVEL (search only among the immediate children of the base object), and SUBTREE (explores the base object and all its descendants). Your choice will be SUBTREE if privacyIDEA must explore all objects under your base DN or LEVEL if your users are located directly under the OU. In my case, LEVEL is enough because my users are not spread across sub-OU structures.
- Base DN : This is the base from which privacyIDEA will search for directory users. In my case, this is the default container located at
CN=Users,DC=it-connect,DC=local. - Server URI : This is a standard format for connecting to an LDAP server. Fill it in using the format "
ldap://fqdn" or, if needed, "ldap://ip". If you have a working LDAPS configuration, use "ldaps://fqdn_or_ip:636" to specify LDAP combined with TLS over port 636. It is also possible to specify multiple domain controllers by separating the URIs with a comma and a space.

- Sections "Credentials" and "Settings"
- STARTTLS : In my case, I uncheck it because I do not have a valid certificate on the server. However, I strongly encourage you to use STARTTLS or LDAPS because otherwise the traffic is sent in cleartext over the network. I also recommend keeping "Verify TLS" checked if you use LDAPS or STARTTLS to verify that the certificate was issued by a trusted root authority.
- Bind DN: This field identifies the service account used to query the directory. In my case, it is the "Sync_PrivacyIDEA" account, which has no rights except read access to the directory. Do me a favor: do not give administrator rights to this service account!
- Bind Password: Service account password
- Bind Type: Simple
- Timeout: This is the number of seconds privacyIDEA will wait for an LDAP operation before giving up. This setting prevents a request from staying blocked too long.
- Size Limit: This number corresponds to the maximum number of LDAP entries a search may return.
- Cache Timeout : privacyIDEA has a cache to keep previously performed user queries in memory and improve performance.
- Server pool retry rounds: number of full rounds privacyIDEA will attempt across the LDAP server list before giving up on the request.
- Server pool skip timeout (seconds): duration for which an unavailable LDAP server is set aside before being retried.

Finally, click the "Preset Active Directory" button to automatically fill in the filters and attributes to use for an Active Directory directory. By default, privacyIDEA uses the sAMAccountName attribute to identify user logins. You can however use userPrincipalName if needed.

Then click on "Test Connection" to test your configuration. A message indicating that the connection was successful, followed by the number of entries detected, should appear.

Click on "Save" to save the changes.
Creating a realm
For users from the resolvers to appear in the privacyIDEA interface, it is necessary to create a realm.
A Realm is a logical grouping of one or more user resolvers. It makes it possible to bring together users from different sources within the same logical space.
For example, you can create a realm called it-connect.local that groups:
- An LDAP resolver connected to an Active Directory directory;
- An SQL resolver containing another user population.
privacyIDEA will then search for users in the it-connect.local realm across all associated resolvers.
Realm creation is done in the "Users" > "Realms" menu. In the "Resolvers" field, choose the LDAP resolver created previously. It is possible to create the realm from resolvers present on multiple privacyIDEA nodes or locally.
In this case, nothing changes because we only have one node. It is also possible to assign a priority to resolvers. This priority ranges from 1 to 999, and the default value is 1000, with the lowest value being the resolver with the highest priority.
Then give your realm a name and click the "Create" button.

Now that the realm is created, verify that the users are coming through by clicking the "Users" > "Overview" menu.

Setting up policies
The application allows you to define "policies" to tell privacyIDEA how to react and behave when it receives a request. Each Policy has a name, a scope, one or more conditions, and one or more associated actions.
The scopes are, in a way, the application's “domains” and determine when and in what context the policy will apply. There are currently 11 available scopes:
- Admin policies: These policies are used to regulate the actions that administrators are allowed to perform.
- User policies: User policies define the actions users are allowed to perform on their own portal when they log in to it.
- Authentication policies: Authentication policies allow you to better control how users authenticate.
- Authorization policies: These are policies related to user permissions management.
- Enrollment policies: The enrollment scope lets you control actions related to token enrollment, whether performed by an administrator or by a user.
- WebUI policies: WebUI stands for "Web User Interface"; these are policies related to the expected behavior of the web page.
- Register policy : This scope is deprecated and is meant to disappear in future releases of the solution. It allows a user who does not exist in any realm or resolver to sign up and create their own account.
- Container policies: We will see what containers are a bit later in the article (not Docker...), these policies make it possible to frame and configure direct interactions between a physical device (the container, such as a smartphone) and the privacyIDEA server.
- Token policies : The token scope is used to define global rules about token behavior and token management.
- Hardening policies: The goal of this scope is to reduce the amount of information privacyIDEA exposes to unauthenticated clients.
- Conditional access policies : This scope makes it possible to detect too many login failures and to react automatically. These policies are especially useful to help limit brute-force attacks.
We will set up a few policies together to explore how they work. However, I will not detail every scope. I encourage you to use the documentation to build policies tailored to your needs and context.
To help us set up policies, privacyIDEA provides several templates available in the "Policies" > "Create Policy" menu by clicking the " Policy Templates" button.

The first policy we will create will hide the welcome message that appears every time we log in to explain how great open source is. Even if that is true, being reminded of it on every login is a bit annoying.

It turns out that an existing template is available. By clicking the "hide_welcome" template, information will be filled in automatically.

You will notice that the name of the policy, the scope, the condition, and the action were filled in automatically. It is also possible to assign a priority and a description.
In the "Condition" tab, you will see that the policy applies to all users since no filter is present. I could have applied it only to users in my realm and my dc01.it-connect.local resolver, and in that case my Administrator user would still see the pop-up at every login.
It is also possible to add "environment" conditions, including:
- privacyIDEA Nodes: limits the policy to one or more specific nodes in a clustered deployment.
- Valid time: limits its application to certain days and time ranges, for example Monday through Friday, from 8 a.m. to 6 p.m.
- Client: filters by the client IP address, with support for subnets.
- User Agent: filters by the software or plugin sending the request. privacyIDEA compares the name only, regardless of version; Add Custom User Agent lets you add one.
Finally, it is possible to add additional conditions to meet specific needs based on a key, an operator, and a value.

Let’s then go to the "Action" tab. As the name suggests, this tab lets you define the behaviors to apply if the policy conditions are met. Inside, you will find all available actions provided by the "WebUI" scope. The policy’s action is clearly indicated, and you can add other actions related to the WebUI scope.
Once we consider the policy properly configured, we can save it by clicking "Save".

After I logged in again, the pop-up did not appear.
Let’s set up another policy, this time in the "enrollment" scope to limit the number of active tokens available per user.
By clicking "Create New Policy", I give it a clear name such as "limit_users_tokens" and define the "enrollment" scope. In terms of conditions, I want this policy to apply to users in my realm "it-connect.local" and to my resolver "dc01.it-connect.local".

In the "Action" tab, expand the "token" action group to find the "max__active_token_per_user" parameter. You can use privacyIDEA’s search bar to make this easier.
After finding the parameter, I set the value to "2", which means my users can have a maximum of two active tokens assigned. Click the "+" button to add it to the policy actions.

You can do the same to allow users to benefit from self-service for their tokens using the "user" scope. For the conditions, I kept the same ones as in the previous policy, namely that it only applies to the it-connect.local realm. In terms of actions, I defined a list of actions the user can perform independently when logging in to the portal:

Another interesting policy lets the user log in for the first time when they have no token available. The onboarding_no_token policy, using the "authentication" scope, allows a user to authenticate to privacyIDEA when they do not have a token available. This option avoids requesting the token while still verifying the password against the Active Directory domain controllers. The term "userstore" refers to the configured Active Directory resolver and/or another user source.
Warning! If you have given your users the ability to delete their tokens and they delete all of them, they will be able to bypass your MFA policy thanks to this policy. In any case, it is better for a technician to assign a token to an employee when they join the company.

Managing administrator rights
Let’s move on to setting up administration profiles such as "Technician" or "Administrator" in privacyIDEA by relying on Active Directory groups and policies.
privacyIDEA does not provide rights management by matching a privacyIDEA group/profile to an Active Directory group the way most tools such as GLPI or Zabbix do. I will use a diagram to help you better understand how administrator rights are managed in the application.

We consider as "Administrators" all people who have extended rights assigned through the "admin" scope. There are two ways to have administrator accounts:
- The first way is to create a user directly in the internal MySQL database with the "
pi manage admin add IDENTIFIANT" command. This is how we created the account we are currently logged in with. In this case, policies can be applied to local administrators by naming them explicitly in the policy conditions. - The second way, which we will use, is to rely on an external resolver and a realm as we did with the "it-connect.local" realm and the "dc01.it-connect.local" resolver. However, there is a major difference: the created realm must be declared as
"SUPERUSER_REALM" in thepi.cfgfile so that privacyIDEA considers the users to be administrators.
We cannot declare the existing it-connect.local realm as a SUPERUSER_REALM, because that would mean all users would be administrators, which is a problem... We will therefore create two different realms and two LDAP resolvers (based on the same domain controllers):
- A realm named "pi-helpdesk", associated with the resolver "dc01-helpdesk.it-connect.local", which will grant rights to technicians.
- A realm named "pi-administrators" associated with the resolver "dc01-administrators.it-connect.local", to grant rights to administrators.
Let’s begin by creating the resolvers.
In "Users" > "Resolvers", note the configuration of your current resolver and then click "New Resolver". The configuration for the other two resolvers will be exactly the same with a few adjustments.
For the first resolver dc01-helpdesk.it-connect.local, I changed the base DN because my IT team accounts are located in a different OU than the standard users, and I added the following filter for my LDAP search: (sAMAccountName=*)(objectCategory=person)(memberOf=CN=NOMDUGROUPE,OU=Groupes,OU=IT,DC=it-connect,DC=local).


As for dc01-administrators.it-connect.local, I only changed the group name in my LDAP filter.

Then click the "Realms" menu, create the two realms, and assign the corresponding resolvers to them:

We will now modify the pi.cfg file to add our two realms to "SUPERUSER_REALM". You can remove the two realms present by default, they are not used.

Restart Apache with the following command:
sudo systemctl restart httpdBefore moving on to policy configuration, we need to add a temporary policy for our local administrator. Indeed, once an "admin" scope policy is defined, local administrators no longer have full powers. It is therefore necessary to create a full-privilege policy for our current administrator.
Click "Create New Policy", then "Show Template" and select "superuser". In the "Admin Name" text field, type your administrator username, press the "+" button, and save the policy.

To avoid making the tutorial more complex and because the goal is to show you how administrative rights are assigned, I will rely on the "helpdesk" and "superuser" templates provided by privacyIDEA, and we will focus on the "conditions". After clicking the "helpdesk" template, the admin scope is automatically set.
We can then choose an "Admin-Realm" to which the policy will apply; here it is the technicians, so I choose "pi-helpdesk". I do not want technicians to be able to perform administration actions on administrators or on other technicians, so I restrict the policy to the it-connect.local realm.

For the administrator policy with the "superuser" template, I choose the "pi-administrators" realm for the Admin Realm. For the User Realm, I select both of my realms so that administration actions can be used on users from the it-connect.local realm (standard users) and those from the helpdesk realm.

This segregation by realm implies a few changes when logging in to privacyIDEA. Let’s take a technician. When they want to log in, they will have two options:
- Log in as a "self-service" user via the identifier: login@it-connect.local.
- Log in as a technician with their administrative account via: login@pi-helpdesk. If it is an administrator, the principle is the same with login@pi-administrators.
privacyIDEA provides a feature to display the available realms on the login page for authentication. This is the
realm_dropdownparameter in the "webui" scope. A simple policy lets you enable it. This option can also be restricted to a predefined list of realms. If you choose to enable it, I strongly recommend applying it only to technicians/administrators so as not to reveal the list of realms.
At this stage, logging in with an administrator or technician account should work with: login@administrative_realm and the Active Directory password.


You can now disable the temporary policy that protected the local administrator in order to use your AD administration accounts.
privacyIDEA Credential Provider
privacyIDEA Credential Provider is an open source plugin provided by NetKnights, the solution vendor, that allows you to request an additional second authentication factor directly at Windows logon. An MSI is also provided by the vendor.
Be careful before deploying it across your entire environment: the Credential Provider is one of the plugins subject to a usage limit without a subscription: it works for free as long as privacyIDEA has no more than 50 users with an active token. Beyond that, some plugin requests are rejected with the error No subscription for your client.
The MSI can be downloaded from the project’s GitHub page at the following link: privacyIDEA Credential Provider.

When running the MSI, click "Next" until you reach this configuration page. Set the login URL and the default realm "it-connect.local". You can also check the option "Send the UPN if detected in username field..." if your environment explicitly uses UPNs for privacyIDEA authentication.
If you do not have a certificate trusted by a certification authority (internal or external), select the "Unkown CA" option. This is obviously valid only in a lab and is not suitable for production. Another option (the one I used) is to import the previously generated self-signed certificate into the workstation’s Trusted Root Certification Authorities store.
Rest assured, the options you provide during installation can later be changed in the Registry Editor.

After clicking "Next", you can define what the application will display when the user logs on. I personally suggest the following options:
- Logo: lets you display the logo of your choice in .bmp format (version 3) and at 128 x 128 pixels. The logo must remain constantly available at the location provided after installing the privacyIDEA Credential Provider. I personally stored it in
C:\privacyIDEA\. - Prompt for username and password first: changes the order of authentication steps so that the username and Active Directory password are requested first, followed by the MFA second factor. Without this option, the order is: username, MFA, then Active Directory password.
- Send domain password to privacyIDEA: sends the Active Directory password to the privacyIDEA server. This option is especially required to use the onboarding_no_token policy so that a user with no token can be authenticated directly against Active Directory.
- Show an option to reset authentification: displays an option to restart the authentication process, especially after a failure.
- Prefill username with last logged-in user: pre-fills the last user who logged in on the machine when attempting to reconnect.
- Hide the username and domain when locked: hides the user and domain when the workstation is locked.

The next window is very important and defines in which cases the privacyIDEA Credential Provider will intervene. It can be configured for three scenarios:
- Logon: when logging in to a Windows session.
- Unlock: when unlocking an open Windows session.
- CredUI: when a login window appears, such as when running an application as Administrator.
By default, privacyIDEA applies to all local scenarios on the workstation and remote ones (RDP) but still allows another authentication method to be used, such as Windows authentication. However, you can define when MFA is enforced or not by checking the "Enable Filter" box.
I will personally enable it and keep it set to "local and remote" for my three scenarios.
It is also possible to enable the privacyIDEA Credential Provider in Safe Mode. I do not necessarily recommend it.

A major point of caution must be considered: with this configuration, only the privacyIDEA Credential Provider will be able to authenticate users and, as a result, it will not be possible to authenticate with local accounts because an OTP will be required. The on_boarding_no_token policy will not apply either because it does not know your user.
To exclude a specific account or group (local or AD), you can add an exclusion for a SINGLE account or for a given group by modifying a value in the Registry Editor. Here are the two commands to run in CMD before restarting the workstation and after installing the Credential Provider:
# For a SINGLE account
reg add "HKLM\SOFTWARE\NetKnights GmbH\PrivacyIDEA-CP" /v excluded_account /t REG_SZ /d "SRV-LOCAL\pi-secours" /f
# For a group
reg add "HKLM\SOFTWARE\NetKnights GmbH\PrivacyIDEA-CP" /v excluded_group /t REG_SZ /d "IT-Connect\pi-secours-group" /fThe fourth configuration page lets you configure FIDO parameters. The fifth page lets you specify the txt or json file to use for storing OTP tokens in offline mode with the privacyIDEA server. Tokens compatible with this mechanism include HOTP and FIDO.
Be careful with the permissions assigned to the file storing offline tokens! It should not be accessible to everyone on the workstation, otherwise people with more or less malicious intent could access HOTP hashes or replace the trusted FIDO public key.
Available parameters include:
- Offline file path: path to the JSON file storing offline authentication data. Default:
C:\offlineFile.json. - Offline threshold: number of remaining OTPs below which the Credential Provider tries to replenish from the server. 25 is the value suggested by the installer.
- Offline try window: maximum number of OTP values compared to the code entered. Default: 10.
- Show token info if an offline token is found: displays information about the available offline tokens for the user. This makes it possible to tell the user that an offline authentication method is available.

Finally, the last page manages expiration through the "Token expiration" setting and deletion through "Delete stale tokens" for locally stored MFA tokens used for offline authentication.
When no value is set, no expiration or deletion will be performed automatically. I recommend configuring these two settings if you plan to provide offline tokens to your users.

To modify the parameters defined during installation, you can use the Windows Registry Editor. You will find all parameters (and others) at the following path:
HKEY_LOCAL_MACHINE\SOFTWARE\Netknights GmbH\PrivacyIDEA-CP
Click "Install" then "Finish" and restart the computer. You should see the privacyIDEA logo or your company logo appear. When you log in, you will see that your user is authenticated directly. This is normal: thanks to the "onboarding_no_token" policy, the user can log in directly when no tokens are available.

Enrolling a TOTP token in self-service
Now that we are logged in for the first time, we can go to the privacyIDEA portal so the user can enroll their first authentication token.
As a reminder, a "TOTP", which stands for "Time-based One Time Password", is a time-based one-time code. On the server and on the device generating the code, the code changes at regular intervals, usually every 30 or 60 seconds.
However, TOTP is subject to two constraints:
- The server and the device generating the code must be synchronized in time.
- Communication is mandatory between the server and the workstation / client service, which means this token cannot be used offline because the server will not be able to validate it.

To enroll the token, log in to the portal with your user account.

Thanks to the configured self-service policy, we can see that only three tabs are available, namely "Tokens Overview" to view tokens, "Tokens Enrollment" for enrollment, and "User Details" which only shows information about the user. By clicking "Enroll a new token", TOTP is automatically selected because it is the only token the user can enroll on their own.
The default values shown to the user (such as the hash algorithm, code length, and so on) for a TOTP token are customizable through a policy, among other things. It is indeed difficult to ask a user to choose an appropriate hash algorithm themselves... Here is an example policy that enforces a "SHA-512" hash algorithm, an 8-character length, and a 60-second rotation for TOTP users:

The user will still be able to "customize" these options from their point of view, but the policy will enforce the settings.

When you click "Enroll Token", a QR code to scan appears to provision the TOTP token. In itself, any MFA authenticator app such as Microsoft Authenticator would work. However, privacyIDEA provides an app for iOS and Android called "privacyIDEA Authenticator". After scanning the QR code with the app, the token appears:


It is possible to rename the token in the app by selecting it, swiping to the right, and clicking "Edit".
On the privacyIDEA web page, by clicking on "Token Overview", you will see that the token appears correctly in the privacyIDEA server interface. Clicking it provides token details.

Now that my user has a token available, if I lock the session, the TOTP code will be requested.

Enrolling an offline HOTP token
In some cases, your user may need to use their workstation without being able to contact the privacyIDEA server.
The solution to this problem is to deploy authentication tokens that can be used without a direct connection to the privacyIDEA server. For this tutorial, we will look at a relatively simple example, namely HOTP. HOTP, which stands for "HMAC One Time Password", is an algorithm that generates one-time codes based on a counter and a shared secret between the server and the application generating the codes. With each successful authentication, the counter increments, making the previous code unusable.
In a classic setup, HOTP requires communication between the client and the server to validate that the code matches. However, as you saw during the installation of the privacyIDEA Credential Provider, it is possible to ask the server for a specific number of tokens that can be used offline. The server then sends the hashes of the next codes associated with a counter value. When a code is entered, the client locally checks whether it matches a stored hash. It can therefore validate it without receiving the shared secret.

Although HOTP is practical for understanding and testing offline authentication, privacyIDEA no longer recommends it for this scenario:
- The main problem is that reserving codes for a PC advances the server counter, which prevents them from being used on another workstation or another service.
- In addition, the local reserve runs out and must be renewed by connecting to the server with a HOTP code when the server is online.
For a production deployment, the vendor instead recommends using FIDO/WebAuthn/Passkey tokens, which do not rely on pre-reserving a series of one-time codes and can be used both online and offline. For our demonstration, and with an administrator profile (since the user is only allowed to enroll TOTP tokens, according to my policies), I enrolled an HOTP token for my user.

A QR code then appeared, which I scanned with the app, and the HOTP token appeared.

To retrieve tokens in advance and use them in offline mode, you must log in once with the HOTP code provided with the available privacyIDEA server. Before doing that, and so the server can send us the HOTP hashes locally to the workstation, some token parameters need to be changed.
On the server side, in the "Tokens Overview" menu, click the created token:
- Max Count: maximum number of authentication attempts before the token is locked.
- Count Window: HOTP value window, used to tolerate a few generated codes that have not yet been used.
- Sync Window: no forward counter to find the application’s position in case of desynchronization.
Select " Use Offline".

A window will appear with two parameters:
- Count: the number of offline tokens issued during the first authentication. Here, around a hundred will be issued at the first login. For token renewal, this will depend on the settings entered during the Credential Provider installation.
- Rounds: the number of PBKDF2 iterations used to hash each HOTP code prepared for offline use. The higher the number of
Rounds, the more expensive it is to test a stolen hash, and the more offline login verification may slow down. I personally left the default value.

You can now log in once with the HOTP code to receive the codes that can be used offline from the privacyIDEA server. Once the code is entered, you must click the arrow in the app so that the code changes and the counter increments. This is an action that must be performed each time an HOTP is used.
You also need to be careful not to click the arrow too many times without consuming the code in the privacyIDEA Authenticator app, otherwise the counter between the server and the application will become unsynchronized despite the margin provided. If you inspect the offline_token.json file defined during application installation, you can see the HOTP hash and the expiration date.

Do not forget to check the permissions on this file. It is sensitive, so only grant rights to the SYSTEM user and an administrators group if needed.
By disconnecting the network on my virtual machine, the offline login worked perfectly.


Additional features
privacyIDEA is a full-featured tool that also offers several capabilities I did not cover in the article but that are worth highlighting.
Containers
In privacyIDEA, a container represents a device that groups multiple tokens, for example a phone with an HOTP token and a TOTP token, allowing centralized management of tokens. The main benefit is device management: if the user loses their phone, the administrator can disable all tokens in the container in a single operation. For existing users with assigned tokens, you can attach them to the container by selecting your user and adding their tokens.
You can then manage the whole container through the "state" field.

Machine Resolver
The "Machine Resolver" follows the same principle as the "User Resolver", except that it allows you to retrieve machines either from a local file (/etc/hosts for example) or from an LDAP directory such as Active Directory or OpenLDAP.
The configuration is fairly similar to the User Resolver with a few details. It can be useful in several scenarios, such as decrypting an encrypted Linux disk with a YubiKey or finding directory servers in order to associate authorized SSH public keys with them. However, I have not seen many documented use cases that actually rely on it.

Event Handler
The Event Handler lets you automate an action when an event occurs in privacyIDEA, with or without conditions. A simple example would be sending an automatic email to the user when an action is performed on one of their tokens (creation, deactivation, etc.).

Periodic Task
Periodic Tasks perform an action at regular intervals, for example every hour.
There are currently two modules provided by privacyIDEA:
- SimpleStat: records the number of tokens every day to track deployment growth.
- EventCounter : records the authentication failure counter every hour (fed by an Event Handler) to track its evolution.

Conclusion
This tutorial is coming to an end. We have taken a tour of the privacyIDEA solution. As you have seen, it is a complete and highly customizable solution that can be integrated into your information system.
In March 2022, a report published by CISA and the FBI, based on industry research, reminded readers that users with MFA are up to 99% less likely to have their accounts compromised. I hope this tutorial has helped you better understand how MFA works and given you the keys to strengthen your access security with privacyIDEA.
Whether you are a student, an enthusiast, an administrator, or a cybersecurity expert, feel free to share your feedback and suggestions on my article. Thank you for reading.


