To run this application yourself download the code and follow the instructions on GitHub.
Adding two-factor authentication (2FA) to your web application increases the security of your user's data. Multi-factor authentication determines the identity of a user in two steps:
- First we validate the user with an email and password
- Second we validate the user using his or her mobile device, by sending a one-time verification code
Once our user enters the verification code, we know they have received the SMS, and indeed are who they say they are. This is a standard SMS implementation.
On this implementation we are just calling
TwilioMessageSender.SendMessageAsync with the verification code message. This class is a wrapper around the Twilio Rest Client, and encapsulates the logic to send an SMS message through Twilio. Let's see how that's done next.
You can find your credentials at your Twilio Account.
Next, we need to register a two-factor provider.
Individual User Accounts authentication provides Two-Factor authentication almost ready out of the box. To setup 2-step authentication you have to register the right provider for your application.
We are registering the
PhoneNumberTokenProvider to send text messages.
Next, let's take a look at how we would send a verification code in an SMS with Twilio.
When a user tries to login, the application needs to make sure the user possesses the phone number they entered.
We have a Two-Factor authentication provider registered, which will be used to to send a 6-digit validation code to validate the login.
Now let's verify the user's code.
The user needs to have logged in with their credentials.
TwoFactorSignInAsync takes care of protecting the application against brute force attacks by using an expirable verification code. If the user enters incorrect codes their account will be locked out.
If the validation was successful the application allows the user to have access to the protected content. Otherwise the application will prompt for the validation code once again.
That's it! We've just implemented an SMS Two-Factor Authenticated application.
If you're a ASP.NET developer working with Twilio, you might want to check out these other tutorials.
Instantly collect structured data from your users with a survey conducted over a call or SMS text messages.
Click-to-call enables your company to convert web traffic into phone calls with the click of a button. Learn how to implement it in minutes.
Thanks for checking this tutorial out! If you have any feedback to share with us, we'd love to hear it. Contact us on Twiiter to let us know what you think.