"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

Create an ASP.NET Web Forms app with SMS Two-Factor Authentication (C#)

by Erik Reitan

Download ASP.NET Web Forms App with Email and SMS Two-Factor Authentication

This tutorial shows you how to build an ASP.NET Web Forms app with Two-Factor Authentication. This tutorial was designed to complement the tutorial titled Create a secure ASP.NET Web Forms app with user registration, email confirmation and password reset. In addition, this tutorial was based on Rick Anderson’s MVC tutorial.

Introduction

This tutorial guides you through the steps required to create an ASP.NET Web Forms application that supports Two-Factor Authentication using Visual Studio. Two-Factor Authentication is an extra user authentication step. This extra step generates a unique personal identification number (PIN) during sign-in. The PIN is commonly sent to the user as an email or SMS message. The user of your app then enters the PIN as an extra authentication measure when signing-in.

Tutorial Tasks and Information:

## Create an ASP.NET Web Forms App

Start by installing and running Visual Studio Express 2013 for Web or Visual Studio 2013. Install Visual Studio 2013 Update 3 or higher as well. Also, you will need to create a Twilio account, as explained below.

[!NOTE] Important: You must install Visual Studio 2013 Update 3 or higher to complete this tutorial.

  1. Create a new project (File -> New Project) and select the ASP.NET Web Application template along with the .NET Framework version 4.5.2 from the New Project dialog box.
  2. From the New ASP.NET Project dialog box, select the Web Forms template. Leave the default authentication as Individual User Accounts. Then, click OK to create the new project.
    New ASP.NET Project dialog box
  3. Enable Secure Sockets Layer (SSL) for the project. Follow the steps available in the Enable SSL for the Project section of the Getting Started with Web Forms tutorial series.
  4. In Visual Studio, open the Package Manager Console (Tools -> NuGet Package Manger -> Package Manager Console), and enter the following command:
    Install-Package Twilio

## Setup SMS and Two-Factor Authentication

This tutorial uses Twilio, but you can use any SMS provider.

  1. Create a Twilio account.
  2. From the Dashboard tab of your Twilio account, copy the Account SID and Auth Token. You will add them to your app later.
  3. From the Numbers tab, copy your Twilio phone number as well.
  4. Make the Twilio Account SID, Auth Token and phone number available to the app. To keep things simple you will store these values in the web.config file. When you deploy to Azure, you can store the values securely in the appSettings section on the web site configure tab. Also, when adding the phone number, only use numbers.
    Notice that you can also add SendGrid credentials. SendGrid is an email notification service. For details about how to enable SendGrid, see the ‘Hook Up SendGrid’ section of the tutorial titled Create a Secure ASP.NET Web Forms App with user registration, email confirmation and password reset.

    [!code-xmlMain]

       1:  </connectionStrings>
       2:    <appSettings>
       3:      <!-- SendGrid Credentials-->    
       4:      <add key="emailServiceUserName" value="[EmailServiceAccountUserName]" />
       5:      <add key="emailServicePassword" value="[EmailServiceAccountPassword]" />
       6:      <!-- Twilio Credentials-->
       7:      <add key="SMSSID" value="[SMSServiceAccountSID]" />
       8:      <add key="SMSAuthToken" value="[SMSServiceAuthorizationToken]" />
       9:      <add key="SMSPhoneNumber" value="+[SMSPhoneNumber]" />    
      10:    </appSettings>
      11:    <system.web>

    [!WARNING] Security - Never store sensitive data in your source code. In this example, the account and credentials are stored in the appSettings section of the Web.config file. On Azure, you can securely store these values on the Configure tab in the Azure portal. For related information, see Rick Anderson’s topic titled Best practices for deploying passwords and other sensitive data to ASP.NET and Azure.

  5. Configure the SmsService class in the App_Start.cs file by making the following changes highlighted in yellow:

    [!code-csharpMain]
       1:  public class SmsService : IIdentityMessageService
       2:  {
       3:      public Task SendAsync(IdentityMessage message)
       4:      {
       5:          var Twilio = new TwilioRestClient(
       6:             ConfigurationManager.AppSettings["SMSSID"],
       7:             ConfigurationManager.AppSettings["SMSAuthToken"]
       8:          );
       9:          var result = Twilio.SendMessage(
      10:              ConfigurationManager.AppSettings["SMSPhoneNumber"],
      11:             message.Destination, message.Body);
      12:   
      13:          // Status is one of Queued, Sending, Sent, Failed or null if the number is not valid
      14:          Trace.TraceInformation(result.Status);
      15:   
      16:          // Twilio doesn't currently have an async API, so return success.
      17:          return Task.FromResult(0);
      18:      }
      19:  }
  6. Add the following using statements to the beginning of the IdentityConfig.cs file:

    [!code-csharpMain]
       1:  using Twilio;
       2:  using System.Net;
       3:  using System.Configuration;
       4:  using System.Diagnostics;
  7. Update the Account/Manage.aspx file by removing the lines highlighted in yellow:

    [!code-aspxMain]
       1:  <%@ Page Title="Manage Account" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Manage.aspx.cs" Inherits="WebFormsTwoFactor.Account.Manage" %>
       2:   
       3:  <%@ Register Src="~/Account/OpenAuthProviders.ascx" TagPrefix="uc" TagName="OpenAuthProviders" %>
       4:   
       5:  <asp:Content ContentPlaceHolderID="MainContent" runat="server">
       6:      <h2><%: Title %>.</h2>
       7:   
       8:      <div>
       9:          <asp:PlaceHolder runat="server" ID="successMessage" Visible="false" ViewStateMode="Disabled">
      10:              <p class="text-success"><%: SuccessMessage %></p>
      11:          </asp:PlaceHolder>
      12:      </div>
      13:   
      14:      <div class="row">
      15:          <div class="col-md-12">
      16:              <div class="form-horizontal">
      17:                  <h4>Change your account settings</h4>
      18:                  <hr />
      19:                  <dl class="dl-horizontal">
      20:                      <dt>Password:</dt>
      21:                      <dd>
      22:                          <asp:HyperLink NavigateUrl="/Account/ManagePassword" Text="[Change]" Visible="false" ID="ChangePassword" runat="server" />
      23:                          <asp:HyperLink NavigateUrl="/Account/ManagePassword" Text="[Create]" Visible="false" ID="CreatePassword" runat="server" />
      24:                      </dd>
      25:                      <dt>External Logins:</dt>
      26:                      <dd><%: LoginsCount %>
      27:                          <asp:HyperLink NavigateUrl="/Account/ManageLogins" Text="[Manage]" runat="server" />
      28:   
      29:                      </dd>
      30:                      <%--
      31:                          Phone Numbers can used as a second factor of verification in a two-factor authentication system.
      32:                          See <a href="http://go.microsoft.com/fwlink/?LinkId=313242">this article</a>
      33:                          for details on setting up this ASP.NET application to support two-factor authentication using SMS.
      34:                          Uncomment the following block after you have set up two-factor authentication
      35:                      --%>
      36:   
      37:                      <dt>Phone Number:</dt>
      38:                      <%--
      39:                      <% if (HasPhoneNumber)
      40:                         { %>
      41:                      <dd>
      42:                          <asp:HyperLink NavigateUrl="/Account/AddPhoneNumber" runat="server" Text="[Add]" />
      43:                      </dd>
      44:                      <% }
      45:                         else
      46:                         { %>
      47:                      <dd>
      48:                          <asp:Label Text="" ID="PhoneNumber" runat="server" />
      49:                          <asp:HyperLink NavigateUrl="/Account/AddPhoneNumber" runat="server" Text="[Change]" /> &nbsp;|&nbsp;
      50:                          <asp:LinkButton Text="[Remove]" OnClick="RemovePhone_Click" runat="server" />
      51:                      </dd>
      52:                      <% } %>
      53:                      --%>
      54:   
      55:                      <dt>Two-Factor Authentication:</dt>
      56:                      <dd>
      57:                          <p>
      58:                              There are no two-factor authentication providers configured. See <a href="http://go.microsoft.com/fwlink/?LinkId=313242">this article</a>
      59:                              for details on setting up this ASP.NET application to support two-factor authentication.
      60:                          </p>
      61:                          <% if (TwoFactorEnabled)
      62:                            { %> 
      63:                          <%--
      64:                          Enabled
      65:                          <asp:LinkButton Text="[Disable]" runat="server" CommandArgument="false" OnClick="TwoFactorDisable_Click" />
      66:                          --%>
      67:                          <% }
      68:                            else
      69:                            { %> 
      70:                          <%--
      71:                          Disabled
      72:                          <asp:LinkButton Text="[Enable]" CommandArgument="true" OnClick="TwoFactorEnable_Click" runat="server" />
      73:                          --%>
      74:                          <% } %>
      75:                      </dd>
      76:                  </dl>
      77:              </div>
      78:          </div>
      79:      </div>
      80:  </asp:Content>
  8. In the Page_Load handler of the Manage.aspx.cs code-behind, uncomment the line of code highlighted in yellow so that it appears as follows:

    [!code-csharpMain]
       1:  protected void Page_Load()
       2:  {
       3:      var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
       4:   
       5:      HasPhoneNumber = String.IsNullOrEmpty(manager.GetPhoneNumber(User.Identity.GetUserId()));
       6:   
       7:      // Enable this after setting up two-factor authentientication
       8:      PhoneNumber.Text = manager.GetPhoneNumber(User.Identity.GetUserId()) ?? String.Empty;
       9:   
      10:      TwoFactorEnabled = manager.GetTwoFactorEnabled(User.Identity.GetUserId());
      11:   
      12:      LoginsCount = manager.GetLogins(User.Identity.GetUserId()).Count;
      13:   
      14:      var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
      15:   
      16:      if (!IsPostBack)
      17:      {
      18:          // Determine the sections to render
      19:          if (HasPassword(manager))
      20:          {
      21:              ChangePassword.Visible = true;
      22:          }
      23:          else
      24:          {
      25:              CreatePassword.Visible = true;
      26:              ChangePassword.Visible = false;
      27:          }
      28:   
      29:          // Render success message
      30:          var message = Request.QueryString["m"];
      31:          if (message != null)
      32:          {
      33:              // Strip the query string from action
      34:              Form.Action = ResolveUrl("~/Account/Manage");
      35:   
      36:              SuccessMessage =
      37:                  message == "ChangePwdSuccess" ? "Your password has been changed."
      38:                  : message == "SetPwdSuccess" ? "Your password has been set."
      39:                  : message == "RemoveLoginSuccess" ? "The account was removed."
      40:                  : message == "AddPhoneNumberSuccess" ? "Phone number has been added"
      41:                  : message == "RemovePhoneNumberSuccess" ? "Phone number was removed"
      42:                  : String.Empty;
      43:              successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
      44:          }
      45:      }
      46:  }
  9. In the codebehind of Account/TwoFactorAuthenticationSignIn.aspx.cs, update the Page_Load handler by adding the following code highlighted in yellow:

    [!code-csharpMain]

       1:  protected void Page_Load(object sender, EventArgs e)
       2:  {
       3:      if (!IsPostBack)
       4:      {
       5:          var userId = signinManager.GetVerifiedUserId<ApplicationUser, string>();
       6:          if (userId == null)
       7:          {
       8:              Response.Redirect("/Account/Error", true);
       9:          }
      10:          var userFactors = manager.GetValidTwoFactorProviders(userId);
      11:          Providers.DataSource = userFactors.Select(x => x).ToList();
      12:          Providers.DataBind();
      13:      }
      14:  }

By making the above code change, the “Providers” DropDownList containing the authentication options will not be reset to the first value. This will allow the user to successfully select all options to use when authenticating, not just the first. 10. In Solution Explorer, right-click Default.aspx and select Set As Start Page. 11. By testing your app, first build the app (Ctrl+Shift+B) and then run the app (F5) and either select Register to create a new user account or select Log in if the user account has already been registered. 12. Once you (as the user) have logged in, click on the User ID (email address) in the navigation bar to display the Manage Account page (Manage.aspx).
13. Click Add next to Phone Number on the Manage Account page.
14. Add the phone number where you (as the user) would like to receive SMS messages (text messages) and click the Submit button.

At this point, the app will use the credentials from the Web.config to contact Twilio. A SMS message (text message) will be sent to the phone associated with the user account. You can verify that the Twilio message was sent by viewing the Twilio dashboard. 15. In a few seconds, the phone associated with the user account will get a text message containing the verification code. Enter the verification code and press Submit.

## Enable Two-Factor Authentication for a Registered User

At this point, you have enabled two-factor authentication for your app. For a user to use two-factor authentication, they can simply change their settings using the UI.

  1. As a user of your app you can enable two-factor authentication for your specific account by clicking on the user ID (email alias) in the navigation bar to display the Manage Account page.Then, click on the Enable link to enable two-factor authentication for the account.
  2. Log off, then log back in. If you’ve enabled email, you can select either SMS or email for two-factor authentication. If you haven’t enabled email, see the tutorial titled Create a Secure ASP.NET Web Forms App with User Registration, Email Confirmation and Password Reset.
  3. The Two-Factor Authentication 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 two-factor authentication 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 two-factor authentication and clicking on the Remember this browser will provide you with convenient one step password access, while still retaining strong two-factor authentication protection for all access from non-trusted devices. You can do this on any private device you regularly use.

## Additional Resources





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-forms/overview/security/create-an-aspnet-web-forms-app-with-sms-two-factor-authentication.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>