Implementing MFA
MFA adds a layer of security by requiring users to provide two or more verification factors to gain access to a resource. The recipe guides you through adding MFA to your FastAPI application, enhancing security by combining something the user knows (their password) with something they have (a device).
Getting ready
For our FastAPI application, we’ll use a time-based one-time password (TOTP) as our MFA method. TOTP provides a six to eight-digit number that’s valid for a short period, typically 30 seconds.
First, ensure you have the necessary packages installed:
$ pip install pyotp
Pyotp is a Python library that implements one-time password algorithms, including TOTP.
To use the TOTP authentication, we need to modify the user table in our database to take into account the TOTP secret used to validate the secret number.
Let’s modify the User
class in the models.py
module by adding the totp_secret
field:
class User(Base): ...