Posted by: Eric Hansen
Just like everything else with IT security, once a gem is found everyone jumps on it. Originally I was going to offer this as a service for my business (still might to a degree), but instead thought I’d share with the Internet how to create yourself a beneficial two-factor authentication system. In the end, you’ll be able to validate authentication requests either via SMS or voice and be proud of the extra power!
While there’s few requirements for this, they should still be addressed:
- SMS & Voice Provider: Twilio
They have been around for a while and give you $20 worth of credit to use for your test number when you sign up. This should be far more than enough for your use as 1 SMS = 0.75 cents and 1 outbound call = 1 cent. While it does cost to also have a number ($1/month/number) its still a valuable service in a small market. Also note that pricing is relative to when I wrote this.
- Language: Python
I am not a pro at Python but it is the easiest I have ever worked with thus far. It also is easier to deploy on various systems.
- Help Libraries: Flask, Peewee and Twilio
Flask is used to process web requests (i.e.: make our Python script act like a minified web server) and Twilio has a Python client/module/helper library that helps us tie very easily into Twilio’s REST API. Peewee makes database connections and such A LOT easier. I won’t go into the mechanics of it but basically its an ORM (object-relational mapper).
- Database: SQLite
Any database will do and I’ll just be covering the table layout here (fields, types, etc…). I’ve since used PostgreSQL after I stopped writing this code and if I did it again I would choose PostgreSQL in a heartbeat. But for a starter guide SQLite is great. After all there’s not a lot of fancy work that needs to be done here.
A sort of pain the butt aspect of Twilio, however, is that numbers have to be in E.164 format. Essentially what this means is that any numbers (even your own Twilio one) that are passed through the Twilio client must be in the format of “+[country code][area code][rest of digits]” so if your Twilio number is 1.234.567.8900 then when you use the API it’d be +12345678900. While its not a big deal it can be annoying to work with at first.
I don’t suggest using the code as is for public use. This was intended for such but back then I was still in the infancy stage. However, this code can be used to build your own as I intend on those who are reading it to take what’s given and run with it at the end.
This guide assumes you have all the mentioned required stuff installed and ready to go.
Twilio does have a tutorial and code for creating a two-factor authentication system using their backend. The major difference between my code and theirs, however, in terms of purpose anyways is that mine generates a random token that has to be entered. You’ll see more of what I’m talking about when we get deeper into everything. The next part will cover setting up Twilio for use.