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.
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.
Create a new F# Console Project with the name Suave.TwoFactorAuth and use Paket to install the following dependencies.
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.
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
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’sVerifyTotp 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.
Property-based testing is one of the powerful technique to unit test the code. Unlike the example-based testing (where we Arrange a set of example inputs to Assert the system under test), Property based testing enable us to focus on what we wanted to test and liberate us from doing mundane work on coming up with sample inputs.
In this blog post, you are going to learn how Property-based testing has helped me and why you need to consider using(or learning) it
Let me start with the use case that I wanted to test. The library that I am working is an adapter between two HTTP protocol abstractions, System.Net.Http and Suave.Http
The first task is to map HttpStatusCode of System.Net to the HttpCode of Suave.Http and the next task is doing the vice-versa.
HttpStatusCode is an enum type and HttpCode is a discriminated union type. Refer this blog post to know more about this difference.
Identifying the Property
The first step is Property-based testing is identifying the property. In other words, it forces to think about the relationship between the input and the output.
I believe this thinking will make a huge difference in the quality of the software that we deliver.
In the first task that we are about to implement, the relationship is the integer representation of the HTTP status code is both HttpStatusCode and HttpCode.
Programmatically, this can be asserted like
// boolean condition// In F# (=) operator represents the equality checkingLanguagePrimitives.EnumToValuehttpStatusCode=httpCode.code
The EnumToValue returns the integer value associated with the enum, which is nothing but the integer representation of the HTTP status code it represents. The code is a member ofHttpCode that represents the same integer.
If this property holds true for given set of inputs, then we can assert that the function that does the transformation is working correctly.
Implementing the mapping function httpStatusCode
The initial implementation that I had in my mind was
If I haven’t choosen to use Property based testing, I might have ended up with this line by line mapping for all the HTTP status codes. As a matter of fact, in my last blog post on using Suave in Azure Functions, I’ve used this same approach.
While thinking regarding properties to assert the transformation, for the first time I came to know about the Language Primitives module in F# and the EnumToValue function.
There should be an another function EnumOfValue right?
Let’s use this in the httpStatusCode function implementation
The reason for this failure is Suave (up to v1.1.3) doesn’t have the HTTP status code 306 (UnUsed). The unit test that we wrote was exercised by the FsCheck for the all possible values of the HttpStatusCode enum till it encountered this failure case.
In this blog post, you are going to experience a scaled up version of Azure Functions in F# using Suave
What’s in the Function Signatures?
In a functional programming language, we define small functions that do one thing well and then we compose them together to represent the solution. To compose functions, we need to be thoughtful while designing the signature of a function.
The Run function takes a HttpRequestMessage and returns the HttpResponseMessage. This signature is simple, but it has a limitation. The limitation has been showcased in the templates directory of Azure Webjobs SDK
My each C, R, U, D are in different functions. Well, there is nothing wrong here. These templates are suitable for getting started in Azure Functions. But what will you do if you have a requirement to expose CRUD of a resource as an Azure Functions?
One option is to define each part of the CRUD as separate Azure Functions (as defined by the templates). If you choose to go by this, you will have four different endpoints and I am sure your client code will have a hard time to consume these endpoints. In addition to this, you will also need to manage four things to satisfy your one requirement.
The other option is putting the CRUD inside a single function.
The Async represents that the WebPart function is a non-blocking asynchronous function and option type models the WebPart which doesn’t handle the HTTP request
The real power of Suave is its set of combinators to manipulate route flow and task composition. You can define an API in Suave that only handles HTTP POST requests and returns Hello as text without typing too much.
If you notice the binding app itself is a WebPart (which in turn a function) with the signature HttpContext -> Async<HttpContext option>. So, you can call this function in your application code and project the output of the function to any output medium that you wish.
The Azure Functions do an incredible job in helping you to define a part of your system as a function. Suave takes it to the next level by helping you to define your system as function.
In nutshell, Suave complements Azure Functions and helps you to define your system as a Serverless Function
Creating a Suave Adapter
So, to scale up Azure Functions using Suave, all we need is an adapter.
The adapter does the following
Transforms HttpRequestMessage from System.Net.Http to HttpRequest of Suave.Http
Then create an empty Suave’s HttpContext with the above HttpRequest and call the WebPart (that represents your system).
The final step is converting the HttpResult of Suave.Http to HttpResponseMessage of System.Net.Http.
This blog post is a proof of concept to use Suave in Azure Functions. There are a lot of improvements to be made to make it production ready. I am planning to publish this as a NuGet package based on the feedback from the community.
I’m delighted to share that I’m running a tutorial at Progressive F# Tutorials 2016, London on Dec 5, 2016. I’m excited to share my experiences with Suave and help developers to understand this wonderful F# library.
The Progressive F# Tutorials offer hands-on learning for every skill set and is led by some of the best experts in F# and functional programming