Implementing Two-Factor Authentication in Suave
Two-factor authentication is a type of Multi-factor authentication which adds an extra layer of security to the applications.
Google Authenticator is one of the popular application that implements two-factor authentication services. In this blog post, we are going to learn how to implement Two-factor authentication in web applications developed using suave
The idea presented here is a naive implementation of Two-factor authentication. The objective here is to demonstrate how to implement it in a functional programming language, F#. Things like TLS/HTTPS, preventing CSRF and other attacks are ignored for brevity.
This blog post is a part of fsharp advent calendar 2016.
Prerequisite
This blog post assumes that you are familiar with the concept of Two-factor authentication and Google Authenticator.
If you would like to know more about these, check out the below resources to get a picture of what it is all about.
We are going to use Time-based One-time Password(TOTP) algorithm in this blog post
What we will be building
We are going to build a tiny web appliaction that has an inbuilt user account with the username foo
and the password bar
After successful login, the user redirected to the Profile page where the user sees his name with a couple of buttons. One to enable Two-factor authentication and another one to log out
Upon clicking the Enable Two Factor Authentication button, the user redirected to the Enable Two Factor Authentication page where the user has to scan the QR Code with the Google Authenticator App (For Android or iPhone). Then he needs to enter the verification code to enable Two-factor authentication for his account.
Google Authenticator App
If the verification code matches, the updated Profile page will look like
Now if the user logout and login again, he will be prompted to enter the verification code
After entering the verification code from the Google Authenticator, the user will be redirected to his Profile page.
Getting Started
Create a new F# Console Project with the name Suave.TwoFactorAuth and use Paket to install the following dependencies.
paket.dependencies
1 2 3 4 5 |
|
Then reference them in the Suave.TwoFactorAuth project.
Suave.TwoFactorAuth/paket.references
1 2 3 4 5 |
|
The OtpSharp is an .NET library that we will be using to generate keys and to verify the verification code from Google Authenticator app using the TOTP algorithm.
The reference to DotLiquid library is required to render the templates using Suave.DotLiquid
Initializing DotLiquid
To use DotLiquid to render the views in Suave, we need to set the templates directory explicitly.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
In this sample application we are going to create a directory views. This views directory will contain the liquid templates of our appliaction
Serving the Login Page
Let’s start by serving the Login page.
Create a new directory with the name views in the Suave.TwoFactorAuth project and add a new liquid template page.liquid. This page.liquid is the master template for our application
After creating, change the ‘Copy to output’ property of the page.liquid file to ‘Copy if newer’ so that the view files copied to the build output directory.
This step is applicable for all the other view templates that we will be creating later
If you are using VS Code or atom editor, you need to do this property change manually by opening the Suave.TwoFactorAuth.fsproj file
1 2 3 4 5 6 7 8 9 10 |
|
Then create a new template file login.liquid in the views directory
The login.liquid view extends the page.liquid view and fill the placeholders for head
and content
.
To display the error messages like Password didn’t match, login.liquid view bounded to the model of type string
.
Now we have the view template for the login page ready and the next step is to render it upon receiving an HTTP request.
Create a new fsharp source file Login.fs and update it as below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
As a good practice let’s create a new module Web
which will be containing all the WebParts of the application
1 2 3 4 5 6 7 |
|
Then start the Web Server
1 2 3 4 5 6 7 8 |
|
Keeping all the Suave WebParts in a single place like we did in the
Web.fs
file, enable us to host Suave in Azure Functions or Asp.Net Core without doing any significant changes.
Handling User Login
To handle the login request from the user, we need to have some users in the application. Let’s hardcode a user account.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Post successful login, to serve the subsequent requests we need to identify the user who logged in. We can achieve it Suave using statefulForSession
, which initializes a user state for a browsing session.
Let’s create some helper functions to do this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
The sessionSet
function takes a WebPart and a key value pair and tries to persist the value in the session state with the given key. If it fails, it calls the WebPart.
The sessionGet
function takes a success WebPart Combinator, a failure WebPart, and a key. If retrieving the value from session state is successful it calls the success WebPart combinator with the retrieved value. In case of retrieval failure it calls the failure WebPart
The clearSession
function clears the state. We will be using it while implementing log out
Now we have all the building blocks for handling user login request, and it’s time to start its implementation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
|
The key function to note here is secured
that takes a WebPart. It calls this WebPart only if the user has logged in. If he didn’t the user will be redirected to the Login page
After successful login, we need to redirect the user to his profile page. Let’s create a profile.liquid
a view template for the Profile page
To render this profile page let’s add some code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
|
The labels IsTwoFactorAuthEnabled
, SecretKey
are just blank right now, and we will be seeing them in action while adding two-factor authentication
The notfound.liquid
page that is going to our fancy 404
page
1 2 |
|
The final step is to put these WebParts together
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Handling Logout
Handling logout is a simpler task as we have all the infrastructure already in place.
1 2 3 4 5 6 7 8 9 10 11 |
|
Enabling Two-factor Authentication
To enable Two-factor authentication, we need to change our User
domain model first.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
The next step is to define a liquid view template for the enable_two_factor
page.
While enabling the Two-factor authentication, we need to generate a secret key for the user that will be required for both, one-time verification code generation as well as its verification.
So, in the enable_two_factor.liquid template we pass the generated SecretKey
as a hidden
input which will then be used for the verification of the code.
1
|
|
Now we need to render the enable_two_factor
page in response to the HTTP GET request /enable_two_factor
Let’s create a new module GoogleAuthenticator
to put the Two-factor authentication related functions together
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
|
As we did in the login page, we are using the err
query string in the request to pass the verification code mismatch errors.
We are leveraging the OtpSharp
library to generate the URL that is in turn represented as a QR Code.
If you would like to how Google Authenticator interprets the generated key and the issuer name from the URL embedded in the QR Code, check out the UriFormat documentation.
The last step in rendering this page is adding the googleAuthenticatorWebPart
in the Web
module where we are putting all the WebParts together
1 2 3 4 5 6 7 8 9 |
|
While enabling Two-factor authentication, the user has to scan the QR-Code from his Google Authenticator app and he will be getting a one-time verification code like this upon adding
Then he will be entering this in the enable_two_factor
page and click Enable
.
Let’s handle this POST request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Thanks to the OtpSharp library for making our job simpler here. We just need to get the SecretKey
, and the Code
from the POST request and get it verified using OtpSharp’s VerifyTotp function.
If the verification is successful, we will be enabling the Two-factor authentication for the user in our in-memory backend using the enableTwoFactorAuth
function and then redirect to the redirect path which in this case the Profile page.
1 2 3 4 5 6 7 8 |
|
Login With Two-factor Authentication
The last step is to prompt for the verification code whenever the Two-factor Authentication enabled user tries to log in and verify the one-time verification code before granting the access.
Let’s start by defining the liquid view template auth_code.liquid
for getting the one-time verification code.
1 2 3 4 5 6 7 8 |
|
After username and password verification, the user has to be redirected the auth_code page
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 |
|
We are using a separate session key authCodeSessionKey
to hold the username of the user.
The final step is verifying the one-time verification code (from the Google Authenticator app) entered by the user.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
|
That’s it! We have successfully implemented Two-factor authentication.
The complete source code is available in my GitHub repository