Build an app with SMS and email 2FA Two-factor authentication in Asp.Net MVC
Tags: mvc, aspnet, dotnet, sms
Published: 2023-10-10 10:43:57

Two-factor authentication (2FA) is an excellent way to enhance both the robustness of your authentication system and the user experience with your authentication process. 2FA adds something that a user has to what he knows in the process of checking what he tells himself to be.

Safety is important, just ask any blue check Twitter user. Deploying your own authentication system is time-consuming and involves numerous risks. So, how do you get beyond user identifiers that are nothing more than an email address and a password that is lengthy and probably difficult to remember if it is correct.

Let’s discuss how to build an app with SMS and email 2FA Two-factor authentication in Asp.Net MVC –


## Create the ASP.NET MVC application.

1. Build a new ASP.NET web project and select the MVC template. WebForms also supports ASP.NET Identity, so you can go through similar steps in a web forms application.

2. Let default authentication be the individual user accounts. If you wish to host the app in Azure, select this check box. Later in the tutorial, we are going to roll out Azure. An Azure account can be opened free of charge.

3. Define what project to use SSL.

## Configuring the SMS for two-factor authentication.
This gives advice on how to use Twilio or ASPSMS, but you can use any other SMS provider.

Create a user account with an SMS service provider.

- Register for a Twilio account or an ASPSMS account.

Installation of additional packages or addition of service part numbers.

- Twilio: This provides instructions on how to use Twilio or ASPSMS, however, you can use any other SMS provider.
- ASPSMS: The following service reference must be included:
- Address: https://webservice.aspsms.com/aspsmsx2.asmx?WSDL
- Namespace: ASPSMSX2

## Determine user credentials for the SMS provider.

- Twilio :
From your Twilio Account's Dashboard tab, copy the Account DIS and Auth Token.

- ASPSMS:
In the settings of your account, navigate to Userkey and copy with your password set by yourself.

We shall subsequently store these values on the web. config file by pressing "SMSAccountIdentification" and "SMSAccountPassword".

## Specify SenderID / Original.

- Twilio :
Under the Numbers tab, copy your Twilio telephone number.

- ASPSMS :
On the Unlock Initiators menu, unlock one or more Initiators or select an Alphanumeric Initiator (not supported by all networks).

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

## Transfer of SMS provider IDs in the application.

Make the sender's identification and telephone number available to the application. To keep things simple, we're going to store those values in the web. config file. When we deploy Azure, we can safely store the values in the application settings section on the website configuration tab.

```
            <appsettings>
            <add key="webpages:Version" value="3.0.0.0">
                  <!-- 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">
               </add></add></add></add></add></add></appsettings>
            <system.web>
          
          </system.web>

```

#### Read More: [What Is Html Helper And Explain Textbox Html Helper In Asp.net Mvc](https://www.ifourtechnolab.com/blog/what-is-html-helper-and-explain-textbox-html-helper-in-asp-net-mvc)

## Implement data transfer to SMS provider.
Configuring the SmsService class in the App_Start IdentityConfig.cs

According to the SMS provider used, enable the Twilio or ASPSMS section:

```
                @model MvcPWy.Models.IndexViewModel
                @{
                   ViewBag.Title = "Manage";
                }
                <!-- <h2>@ViewBag.Title.</h2>
                <p class="text-success">@ViewBag.StatusMessage</p>
                <div>
                   <h4>Change your account settings</h4>
                   <hr>
                   <dl class="dl-horizontal">
                      <dt>Password:</dt>
                      <dd>
                         [
                         @if (Model.HasPassword)
                         {
                            @Html.ActionLink("Change your password", "ChangePassword")
                         }
                         else
                         {
                            @Html.ActionLink("Create", "SetPassword")
                         }
                         ]
                      </dd>
                      <dt>External Logins:</dt>
                      <dd>
                         @Model.Logins.Count [
                         @Html.ActionLink("Manage", "ManageLogins") ]
                      </dd>
                        <dt>Phone Number:</dt>
                      <dd>
                         @(Model.PhoneNumber ?? "None") [
                         @if (Model.PhoneNumber != null)
                         {
                            @Html.ActionLink("Change", "AddPhoneNumber")
                            @:  | 
                            @Html.ActionLink("Remove", "RemovePhoneNumber")
                         }
                         else
                         {
                            @Html.ActionLink("Add", "AddPhoneNumber")
                         }
                         ]
                      </dd>
                      <dt>Two-Factor Authentication:</dt> 
                      <dd>
                         @if (Model.TwoFactor)
                         {
                            using (Html.BeginForm("DisableTwoFactorAuthentication", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                            {
                               @Html.AntiForgeryToken()
                               <text>Enabled
                                  <input type="submit" value="Disable" class="btn btn-link" />
                               </text>
                            }
                         }
                         else
                         {
                            using (Html.BeginForm("EnableTwoFactorAuthentication", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
                            {
                               @Html.AntiForgeryToken()
                               <text>Disabled
                                  <input type="submit" value="Enable" class="btn btn-link" />
                               </text>
                            }
                         }
                      </dd>
                   </dl>
                </div> -->

```

#### Looking for Trusted [ASP.Net Development Company](https://www.ifourtechnolab.com/dot-net-development-company)? For Your Business?

Check whether the EnableTwoFactorAuthentication and DisableTwoFactorAuthentication action methods in the ManageController have the attribute[ValidateAntiForgeryToken]:

```
[HttpPost,ValidateAntiForgeryToken]
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");
}
[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");
}

</actionresult></actionresult>

```

```
public ActionResult AddPhoneNumber()
{
  return View();
}

```

- Run the application and sign in with your already registered account.
- Click your User ID, which will enable the Index method of action within. Manage controller.
- Click Add.
- The AddPhoneNumber action method shows a dialogue box to enter a phone number that can receive SMS messages.
- In a few seconds, you will receive an SMS with the verification code. Enter it, then tap Submit.
- Your telephone number has been added to the Manage view.

## Enable Two-Factor Authentication

- In the model-generated application, you must use the UI to enable two-factor authentication (2AF). To activate 2FA, click on your user name (email alias) in the navigation bar.
- Click on enable 2FA.
- Log out and then log in. If you have turned on e-mail, you can select SMS or e-mail for 2FA.
- The Verify Code page appears where you can enter the code (from an SMS or e-mail).

By clicking on the “Remember this browser” checkbox, you will not have to use 2FA to sign in when you use the browser and the device in which you checked the checkbox. Until malicious users can access your device, enable 2FA and click Remember this browser will provide you with convenient password access in a single step, while maintaining a high 2FA protection for all access from unsecured devices.

## Conclusion

In this blog, we learned how to activate 2FA on a new ASP.NET MVC application. We have also gone through Two-factor authentication by text message and e-mail with ASP.NET Identity details with the code behind the sample.