×

iFour Logo

Build an app with SMS and email 2FA Two-factor authentication in Asp.Net MVC

Kapil Panchal - July 15, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
Build an app with SMS and email 2FA Two-factor authentication in Asp.Net MVC

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.

 

Table of Content

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.

            
            
                  
                  
            
            
            
            
            
               
            
          
          
               

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:

public class SmsService : IIdentityMessageService
{
  public Task SendAsync(IdentityMessage message)
 {
  }
}
              

Updating the Manage View Index.cshtml Razor view:


(note: do not only delete comments from the outgoing code but also use the code below.)

            
                @model MvcPWy.Models.IndexViewModel
                @{
                   ViewBag.Title = "Manage";
                }
                
                
            

Looking for Trusted ASP.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 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 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");
}


      
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.

Build an app with SMS and email 2FA Two-factor authentication in Asp.Net MVC 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.   Table of Content 1. Create the ASP.NET MVC application. 2. Configuring the SMS for two-factor authentication. 3. Determine user credentials for the SMS provider. 4. Specify SenderID / Original. 5. Transfer of SMS provider IDs in the application. 6. Implement data transfer to SMS provider. 7. Updating the Manage View Index.cshtml Razor view. 8. Enable Two-Factor Authentication.. 9. Conclusion 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. 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. 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. 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. Read More: 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: public class SmsService : IIdentityMessageService { public Task SendAsync(IdentityMessage message) { } } Updating the Manage View Index.cshtml Razor view: (note: do not only delete comments from the outgoing code but also use the code below.) @model MvcPWy.Models.IndexViewModel @{ ViewBag.Title = "Manage"; } @ViewBag.Title. @ViewBag.StatusMessage Change your account settings Password: [ @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 } } else { using (Html.BeginForm("EnableTwoFactorAuthentication", "Manage", FormMethod.Post, new { @class = "form-horizontal", role = "form" })) { @Html.AntiForgeryToken() Disabled } } --> Looking for Trusted ASP.Net Development Company ? For Your Business? CONNECT US   Check whether the EnableTwoFactorAuthentication and DisableTwoFactorAuthentication action methods in the ManageController have the attribute[ValidateAntiForgeryToken]: [HttpPost,ValidateAntiForgeryToken] public async Task 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 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"); } 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.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Power Apps vs Power Automate: When to Use What?
Power Apps vs Power Automate: When to Use What?

I often see people asking questions like “Is Power App the same as Power Automate?”. “Are they interchangeable or have their own purpose?”. We first need to clear up this confusion...

Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula
Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula

We always hear about how important it is to be competitive and stand out in the market. But as an entrepreneur, how would you truly set your business apart? Is there any way to do...

React 18 Vs React 19: Key Differences To Know For 2024
React 18 Vs React 19: Key Differences To Know For 2024

Ever wondered how a simple technology can spark a revolution in the IT business? Just look at React.js - a leading Front-end JS library released in 2013, has made it possible. Praised for its seamless features, React.js has altered the way of bespoke app development with its latest versions released periodically. React.js is known for building interactive user interfaces and has been evolving rapidly to meet the demands of modern web development. Thus, businesses lean to hire dedicated React.js developers for their projects. React.js 19 is the latest version released and people are loving its amazing features impelling them for its adoption.