Two Factor Authentication using ASP.NET

Posted By :Sonu Kumar |31st May 2022

What is Two Factor Authentication - 

Two-factor authentication is a security layer, that provides a second layer into the application to access specific users by using the Mobile number/ Email OTP verification.

How Does 2FA Work

 2FA transaction happens like this:

  • The user logs in to the website with the username and password
  • An authentication server validates the password, and if it is correct, the user is eligible to use the second factor.
  • The authentication server transmits a unique code to the user's second-factor device.
  • The user confirms their identity by approving the extra authentication from their second-factor device.

I have attached the below code for the implementation of Two-factor Authentication:-

           // For generating the Random number
                Random r = new Random();
                string OTP = r.Next(1000, 9999).ToString();
       

           //Send message format
                string Username = "testemail.com";
                string APIKey = "YourHash";//This may vary api to api. For example, it could be a password, secret key, hash, etc.
                string SenderName = "MyName";
                string Number = "**********";
                string Message = "Your OTP code is - " + OTP;
                string URL = "http://smsapi.smsurlname.in/sendsms/?username=" + TestUserName+ "&hash=" + APIKey + "&sender=" + TestSenderName + "&numbers=" + Number + "&message=" + Message;
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                StreamReader sr = new StreamReader(resp.GetResponseStream());
                string results = sr.ReadToEnd();
                sr.Close();
          
            // Here we are storing the OTP in session to verify on the next page.
            //If we store the OTP into the DB, it takes a lot of time for verification.
             
                Session["OTP"] = OTP;

                //Redirect for varification
                Response.Redirect("OTPAuthentication.aspx");

 

In the above code, I've got generated the OTP of 4 digits, After generating the send the like better to SMS using SMS API with the assistance of HttpWebRequest. For this, you would like SMP API account detail.
After generating OPT I've got stored the OPT in session so redirected to the following page. By doing this we don't have to store the OTP in DB. Just redirect the verification page.

 

Conclusion -

For improving the security and to avoid hacking and all unwanted attack on our application we have to implement a second layer of security into our application.

Thanks


About Author

Sonu Kumar

He is enthusiastic backend developer. Always ready to learning new technologies.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us