Two Factor Authentication using Google Authenticator in own asp.net project?

Pankaj Mishra picture Pankaj Mishra · Apr 26, 2014 · Viewed 8.4k times · Source

Hello I have created own asp.net project (Not MVC). Now I want to implement Two Factor Authentication using Google Authenticator. So when ever user get register user will get key or get QR image and setup with it's android phone. And for login they need key from google authenticator app.

I got few MVC code in asp.net. I need steps to how integrate in asp.net application (Not MVC) Please guide how can i implement this any sample will be appreciated.

Thanks

Answer

Reza Del picture Reza Del · Mar 10, 2015

To Add Google authentication you need the following

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;
using System.Web.Profile;
using System.Web.Security;
using Google.Authenticator;

To get the Google.Authenticator; check here https://www.nuget.org/packages/GoogleAuthenticator

now setting up the Google authentication.

TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
var setupInfo = tfa.GenerateSetupCode("Name of the app", "More info ABout the App", "SuperSecretKeyGoesHere", 300 , 300//the width and height of the Qr Code);

string qrCodeImageUrl = setupInfo.QrCodeSetupImageUrl; //  assigning the Qr code information + URL to string
string manualEntrySetupCode = setupInfo.ManualEntryKey; // show the Manual Entry Key for the users that don't have app or phone
Image1.ImageUrl = qrCodeImageUrl;// showing the qr code on the page "linking the string to image element"
Label1.Text = manualEntrySetupCode; // showing the manual Entry setup code for the users that can not use their phone

you can change the SuperSecretKeyGoesHere to any value that you want, but make sure it has more than 10 character otherwise the manual entry key that is generated will not work. Now you can check the user input with text box and button click

this bit will look at the user entry and see if its ok

string user_enter=TextBox1.Text;
TwoFactorAuthenticator tfa = new TwoFactorAuthenticator();
bool isCorrectPIN = tfa.ValidateTwoFactorPIN("SuperSecretKeyGoesHere", user_enter);
if (isCorrectPIN == true)
{
Label2.Text = "i am cool";

}
else
{

Label2.Text = "i am Fool";
}