pyg2fa : Python Library for using Google Authenticator with your Web App
I have been using Google two factor authentication for a while. It’s probably the reason why I login using my Google id on every possible site I use. I can use a simple mobile app to generate time-sensitive one-time password (OTP) along with my regular password to login.
Google authenticator mobile app allows multiple profiles. This allows any developer to use Google app with their own app authentication system. We just need to develop the server side component to make it work with our web application. It’s not difficult considering Google uses an open standard HMAC-Based One-Time Password (HOTP) Algorithm as defined in RFC 4226.
I spent some time developing python library for the same. It’s a generic library which can be used with any kind of python application. I have a demo web application which kind of gives the flow. The demo application is in no way complete. Don’t use it in your production system.
The block diagram below shows a simple two authentication system using pyg2fa. Your user table contains an extra column called g2fa_code which is a 16 digit, base 32 number used as a seed for OTP. This field should be regarded as a second password field for all practical purposes. So encrypt it.
g2fa_code is unique and randomly generated for every user. It could be generated at the time of registration or at any point when user enables two factor authentication. This is the number used to generate QR code which can be scanned by the user’s Google authentication app. If the user wants to enter the code directly into his Google authenticator app then show him the same. Once it’s added successfully to the app it starts generating OTPs which can be used against a specific app.
On the server side, validation is very easy. Just call
validate(users_g2fa_code, int(user_entered_otp), 4)
It should return True if everything is okay. Make sure the server time is in sync with the internet time. OTPs are highly time sensitive. I have added a third parameter ‘window’ in the validate method which will allow client’s clock to drift server time by +/- defined seconds. Just make sure that that window is not very huge.
To run the demo
1. Install pyg2fa
git clone https://github.com/thejeshgn/pyg2fa cd pyg2fa python setup.py install
2. Run the demo
cd demo python demo.py
Once you run demo.py, it prints steps to follow and interact with the demo app. Play with demo.py. It’s not very difficult to master. Of course fork the project and send me enhancements.