×
iFour Logo

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

iFour Team - July 15, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

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 ? Your Search ends here.

 

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 ? Your Search ends here. See here   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.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Node.js 19 - What changes and effects does it bring to the business?
Node.js 19 - What changes and effects does it bring to the business?

Table of Content 1.What is Node.js? 2.Introducing Node.js 19 with major updates and changes 3.Why should I upgrade from Node 18 to 19? 4.New Features in Node.js...

What are the concerns faced while developing Fitness management software?
What are the concerns faced while developing Fitness management software?

Table of Content 1.Explaining vision to folklores 2.Changing the habits of end users 3.Conflicts with team members 4.The issue of cyber security 5.Identifying issues...

How Blockchain can impact the Financial industry in 2023?
How Blockchain can impact the Financial industry in 2023?

Table of Content 1.Boosts payment transparency, trust, and efficiency 2.Reduces operational risks and enables real-time verification 3.Eliminates central authority to...