Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

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


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.

  1. Register for a Twilio account or an ASPSMS account.

Installation of additional packages or addition of service part numbers.

  1. Twilio :
    1. This provides instructions on how to use Twilio or ASPSMS, however, you can use any other SMS provider.

  1. ASPSMS:
    1. The following service reference must be included:
  1. Address:
    1. https://webservice.aspsms.com/aspsmsx2.asmx?WSDL
  1. Namespace:
    1. ASPSMSX2

Determine user credentials for the SMS provider.

  1. Twilio:
    1. From your Twilio Account's Dashboard tab, copy the Account DIS and Auth Token.
  1. ASPSMS:
    1. In the settings of your account, navigate to Userkey and copy with your password set by yourself.
    2. We shall subsequently store these values on the web. config file by pressing "SMSAccountIdentification" and "SMSAccountPassword".

Specify SenderID / Original.

  1. Twilio:
    1. Under the Numbers tab, copy your Twilio telephone number.
  1. ASPSMS:
    1. On the Unlock Initiators menu, unlock one or more Initiators or select an Alphanumeric Initiator (not supported by all networks).
    2. 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";
}
<!-- <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 ?

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");
}

  1. Run the application and sign in with your already registered account.
  2. Click your User ID, which will enable the Index method of action within. Manage controller.
  3. Click Add.
  4. The AddPhoneNumber action method shows a dialogue box to enter a phone number that can receive SMS messages.
public ActionResult AddPhoneNumber()
	{
	   return View();
	}

  1. In a few seconds, you will receive an SMS with the verification code. Enter it, then tap Submit.
  2. Your telephone number has been added to the Manage view.

Enable Two-Factor Authentication

  1. 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.
  2. Click on enable 2FA.
  3. Log out and then log in. If you have turned on e-mail, you can select SMS or e-mail for 2FA.
  4. 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

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.

  1. Register for a Twilio account or an ASPSMS account.

Installation of additional packages or addition of service part numbers.

  1. Twilio :
    1. This provides instructions on how to use Twilio or ASPSMS, however, you can use any other SMS provider.

  1. ASPSMS:
    1. The following service reference must be included:
  1. Address:
    1. https://webservice.aspsms.com/aspsmsx2.asmx?WSDL
  1. Namespace:
    1. ASPSMSX2

Determine user credentials for the SMS provider.

  1. Twilio:
    1. From your Twilio Account's Dashboard tab, copy the Account DIS and Auth Token.
  1. ASPSMS:
    1. In the settings of your account, navigate to Userkey and copy with your password set by yourself.
    2. We shall subsequently store these values on the web. config file by pressing "SMSAccountIdentification" and "SMSAccountPassword".

Specify SenderID / Original.

  1. Twilio:
    1. Under the Numbers tab, copy your Twilio telephone number.
  1. ASPSMS:
    1. On the Unlock Initiators menu, unlock one or more Initiators or select an Alphanumeric Initiator (not supported by all networks).
    2. 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 = &quot;Manage&quot;;
}
<!-- <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 ?

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");
}

  1. Run the application and sign in with your already registered account.
  2. Click your User ID, which will enable the Index method of action within. Manage controller.
  3. Click Add.
  4. The AddPhoneNumber action method shows a dialogue box to enter a phone number that can receive SMS messages.
public ActionResult AddPhoneNumber()
	{
	   return View();
	}

  1. In a few seconds, you will receive an SMS with the verification code. Enter it, then tap Submit.
  2. Your telephone number has been added to the Manage view.

Enable Two-Factor Authentication

  1. 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.
  2. Click on enable 2FA.
  3. Log out and then log in. If you have turned on e-mail, you can select SMS or e-mail for 2FA.
  4. 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.