SMS and email Two-Factor Authentication in ASP.NET MVC 5

Create an ASP.NET  MVC app

Start by installing and running Visual Studio Express 2013 for Web or  Visual Studio 2013 .  Install Visual Studio 2013 Update 3 or higher.

Warning: You should complete Create a secure ASP.NET MVC 5 web app with log in, email confirmation and password reset before proceeding. You must install Visual Studio 2013 Update 3 or higher to complete this tutorial.
  1. Create a new ASP.NET Web project and select the MVC template. Web Forms also supports ASP.NET Identity, so you could follow similar steps in a web forms app.
  2. Leave the default authentication as Individual User Accounts. If you’d like to host the app in Azure, leave the check box checked. Later in the tutorial we will deploy to Azure. You can open an Azure account for free .
  3. Set the project to use SSL .

Set up SMS for Two-factor authentication

This tutorial provides instructions for using either Twilio or ASPSMS but you can use any other SMS provider.

  1. Creating a User Account with an SMS provider

    Create a Twilio or an ASPSMS account.

  2. Installing additional packages or adding service references

    In the Package Manager Console, enter the following command:
    Install-Package Twilio

    The following service reference needs to be added:



  3. Figuring out SMS Provider User credentials

    From the Dashboard tab of your Twilio account, copy the Account SID and Auth token.

    From your account settings, navigate to Userkey and copy it together with your self-defined Password.

    We will later store these values in the web.config file within the keys "SMSAccountIdentification" and"SMSAccountPassword".

  4. Specifying SenderID / Originator

    From the Numbers tab, copy your Twilio phone number.

    Within the Unlock Originators Menu, unlock one or more Originators or choose an alphanumeric Originator (Not supported by all networks).

    We will later store this value in the web.config file within the key "SMSAccountFrom".

  5. Transferring SMS provider credentials into app

    Make the credentials and sender phone number available to the app. To keep things simple we will store these values in the web.config file. When we deploy to Azure, we can store the values securely in the app settingssection on the web site configure tab.

          <add key="webpages:Version" value="" />
          <!-- Markup removed for clarity. -->
          <!-- SendGrid-->
          <add key="mailAccount" value="account" />
          <add key="mailPassword" value="password" />
          <add key="SMSAccountIdentification" value="My Identification" />
          <add key="SMSAccountPassword" value="My Password" />
          <add key="SMSAccountFrom" value="+12065551234" />
    Security Note: Never store sensitive data in your source code. The account and credentials are added to the code above to keep the sample simple. See Best practices for deploying passwords and other sensitive data to ASP.NET and Azure .
  6. Implementation of data transfer to SMS provider

    Configure the SmsService class in the App_Start\IdentityConfig.cs file.

    Depending on the used SMS provider activate either the Twilio or the ASPSMS section:

    public class SmsService : IIdentityMessageService
        public Task SendAsync(IdentityMessage message)
            // Twilio Begin
            // var Twilio = new TwilioRestClient(
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountIdentification"],
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountPassword"]);
            // var result = Twilio.SendMessage(
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountFrom"],
            //   message.Destination, message.Body
            // );
            // Status is one of Queued, Sending, Sent, Failed or null if the number is not valid
            // Trace.TraceInformation(result.Status);
            // Twilio doesn't currently have an async API, so return success.
            // return Task.FromResult(0);
            // Twilio End
            // ASPSMS Begin 
            // var soapSms = new MvcPWx.ASPSMSX2.ASPSMSX2SoapClient("ASPSMSX2Soap");
            // soapSms.SendSimpleTextSMS(
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountIdentification"],
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountPassword"],
            //   message.Destination,
            //   System.Configuration.ConfigurationManager.AppSettings["SMSAccountFrom"],
            //   message.Body);
            // soapSms.Close();
            // return Task.FromResult(0);
            // ASPSMS End
  7. Update the Views\Manage\Index.cshtml Razor view: (note: don’t just remove the comments in the exiting code, use the code below.)
    @model MvcPWy.Models.IndexViewModel
       ViewBag.Title = "Manage";
    <p class="text-success">@ViewBag.StatusMessage</p>

    Change your account settings

    [ @if (Model.HasPassword) { @Html.ActionLink("Change your password", "ChangePassword") } else { @Html.ActionLink("Create", "SetPassword") } ]
    External Logins:
    @Model.Logins.Count [ @Html.ActionLink("Manage", "ManageLogins") ]
    Phone Number:
    @(Model.PhoneNumber ?? "None") [ @if (Model.PhoneNumber != null) { @Html.ActionLink("Change", "AddPhoneNumber") @:  |  @Html.ActionLink("Remove", "RemovePhoneNumber") } else { @Html.ActionLink("Add", "AddPhoneNumber") } ]
    Two-Factor Authentication:
    @if (Model.TwoFactor) { using (Html.BeginForm("DisableTwoFactorAuthentication", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() Enabled type="submit" value="Disable" class="btn btn-link" /> } } else { using (Html.BeginForm("EnableTwoFactorAuthentication", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() Disabled type="submit" value="Enable" class="btn btn-link" /> } }
  8. Verify the EnableTwoFactorAuthentication and DisableTwoFactorAuthentication action methods in the ManageController have the [ValidateAntiForgeryToken] attribute:
    // POST: /Manage/EnableTwoFactorAuthentication
    public async Task<ActionResult> EnableTwoFactorAuthentication()
        await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
        var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
        if (user != null)
            await SignInAsync(user, isPersistent: false);
        return RedirectToAction("Index", "Manage");
    // POST: /Manage/DisableTwoFactorAuthentication
    [HttpPost, ValidateAntiForgeryToken]
    public async Task<ActionResult> DisableTwoFactorAuthentication()
        await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), false);
        var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
        if (user != null)
            await SignInAsync(user, isPersistent: false);
        return RedirectToAction("Index", "Manage");
  9. Run the app and log in with the account you previously registered.
  10. Click on your User ID, which activates the Index action method in Manage controller.
  11. Click Add.
  12. The AddPhoneNumber action method displays a dialog box to enter a phone number that can receive SMS messages.
    // GET: /Account/AddPhoneNumber
    public ActionResult AddPhoneNumber()
       return View();

  13. In a few seconds you will get a text message with the verification code. Enter it and press Submit.
  14. The Manage view shows your phone number was added.

Enable two-factor authentication

In the template generated app, you need to use the UI to enable two-factor authentication (2FA). To enable 2FA, click on your user ID (email alias) in the navigation bar.

Click on enable 2FA.

Log out, then log back in. If you’ve enabled email (see my previous tutorial), you can select the SMS or email for 2FA.

The Verify Code page is displayed where you can enter the code (from SMS or email).

Clicking on the Remember this browser check box will exempt you from needing to use 2FA to log in when using the browser and device where you checked the box. As long as malicious users can’t gain access to your device, enabling 2FA and clicking on the Remember this browser will provide you with convenient one step password access, while still retaining strong 2FA protection for all access from non-trusted devices. You can do this on any private device you regularly use.



How to Choose A Right Passive UHF RFID Antenna?

We will discuss these factors below to help you better understand UHF RFID passive antennas.


Each country has regulations that specify the frequency ranges for UHF RFID transmissions within that country. The three most prevalent frequency ranges for UHF RFID antennas are:

  • 902-928 MHz (US/FCC)
  • 865-868 MHz (EU/ETSI)
  • 860-960 MHz (Global)

When choosing an RFID antenna, be sure to select the frequency range that is right for your region.


Gain and beamwidth are grouped together because they are both electrical components of an antenna and are distinctly related. The higher the gain, the narrower (or smaller) the beamwidth. Higher gain creates a narrower area of coverage, but the beam will travel a longer distance. Beamwidth and gain are analogous to the beam of a flashlight. Check out the diagram below to see how differences in gain can drastically affect the antenna’s beamwidth.


Beamwidth is determined by gain – the higher the gain, the more focused the beam.

The ideal beamwidth and gain will depend on your specific application. If you have many tags a short distance away, then you most likely don’t need a high gain antenna; it would be more advantageous to use a wide beamwidth antenna with relatively low gain as represented by the third image above.


Most UHF RFID passive antennas are either linearly or circularly polarized. Linearly polarized antennas send RF waves in a single plane either horizontally or vertically. Circularly polarized antennas send RF waves in a circular motion either clockwise or counterclockwise. When the waves rotate clockwise, the antenna is a left-hand circularly polarized (LHCP) antenna; when the waves rotate counterclockwise, the antenna is a right-hand circularly-polarized antenna (RHCP).

When you have a setup where antennas are facing each other, it’s important to know if you have a LHCP or RHCP antennas. When antennas face each other and emit waves in the same direction, waves will create null zones where the two sides meet. If you choose LHCP and RHCP when you have two antennas facing each other, it creates a more effective read zone then if you use two LHCP antennas.


One exception to the rule above is when using a bistatic system. If you use a bistatic system in a portal arrangement (antennas facing each other), the antenna that transmits the RF wave will need to be the SAME polarization as the antenna that receives the RF wave. So if a LHCP transmits the wave, the antenna that receives the RF wave will need to be LHCP in order to receive it most efficiently.

If all the tags in your application will be read the same orientation and at the same height, then it may be best to use a linearly polarized antenna. The main advantage to circularly polarized antennas is that they are better for applications where you cannot predict tag placement or orientation.