ASP .NET Core Two-Factor Authentication

Feb 21, 2024

What is Authentication? 

Authentication is the process of validating the identity of a user or system attempting to access a protected resource. In C# programming, authentication is commonly implemented in various scenarios, including web applications, desktop applications, and services. 

Types of Authentications 

  1. Basic Authentication 

  1. Password-based Authentication 

  1. Multi-Factor Authentication 

  1. Token-based Authentication 

Let’s understand authentication with example. Here I am taking one example of MFA (Two-factor authentication). 

Step 1: Create the MVC Web Application 

Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open. Select ASP.NET Core web app (Model-View-Controller) and press Next and enter project name and click Next

 

 

Choose 'Individual Account' as the authentication type and click 'Create' to generate the project. 

 

 

Step 2: Adding QR Codes to configure two-factor authentication 

We will be using a QR code to configure and sync the Google authenticator app with our web app. Download the qrcode.js JavaScript library from https://davidshimjs.github.io/qrcodejs/ and put it into the “wwwroot\lib” folder in your application. Now, your “wwwroot” folder will have the following structure. 

 

 

Now, Add new scaffolded item in your project by right click on Area folder and select New scaffolded Item under Add section. 

Select Identity section on left sidebar and click on Add

 

 

Now, Select the identity files that you have to add to your project but select file “Account/Manage/EnableAuthenticator” is compulsory for 2FA. 

Select the DbContext Class of your project and click on add.

 

Open the “Views\Manage\EnableAuthenticator.cshtml” file. You will find @section Scripts at the end of the file. Put the following code in it. 

@section Scripts {  
@await Html.PartialAsync("_ValidationScriptsPartial")  
<script src="~/lib/qrcode/qrcode.js"></script>  
<script type="text/javascript">  
new QRCode(document.getElementById("qrCode"),  
{  
text: "@Html.Raw(Model.AuthenticatorUri)",  
width: 200,  
height: 200  
});  
</script>  
} 

 

Note: Change your script path as per your folder structure. 

This “EnableAuthenticator.cshtml” file already has a div with the id “qrCode” (see the code snippet below). We are generating a QR code inside that div using the qrcode.js library. We are also defining the dimensions of the QR code in terms of width and height. 
So finally, your “EnableAuthenticator.cshtml” file will look like this.

@page
@model EnableAuthenticatorModel
@{
    ViewData["Title"] = "Configure authenticator app";
    ViewData["ActivePage"] = ManageNavPages.TwoFactorAuthentication;
}

<partial name="_StatusMessage" for="StatusMessage" />
<h3>@ViewData["Title"]</h3>
<div>
    <p>To use an authenticator app go through the following steps:</p>
    <ol class="list">
        <li>
            <p>
                Download a two-factor authenticator app like Microsoft Authenticator for
                <a href="https://go.microsoft.com/fwlink/?Linkid=825072">Android</a> and
                <a href="https://go.microsoft.com/fwlink/?Linkid=825073">iOS</a> or
                Google Authenticator for
                <a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&amp;hl=en">Android</a> and
                <a href="https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8">iOS</a>.
            </p>
        </li>
        <li>
            <p>Scan the QR Code or enter this key <kbd>@Model.SharedKey</kbd> into your two factor authenticator app. Spaces and casing do not matter.</p>
            <div class="alert alert-info">Learn how to <a href="https://go.microsoft.com/fwlink/?Linkid=852423">enable QR code generation</a>.</div>
            <div id="qrCode"></div>
            <div id="qrCodeData" data-url="@Model.AuthenticatorUri"></div>
        </li>
        <li>
            <p>
                Once you have scanned the QR code or input the key above, your two factor authentication app will provide you
                with a unique code. Enter the code in the confirmation box below.
            </p>
            <div class="row">
                <div class="col-md-6">
                    <form id="send-code" method="post">
                        <div class="form-floating mb-3">
                            <input asp-for="Input.Code" class="form-control" autocomplete="off" placeholder="Please enter the code."/>
                            <label asp-for="Input.Code" class="control-label form-label">Verification Code</label>
                            <span asp-validation-for="Input.Code" class="text-danger"></span>
                        </div>
                        <button type="submit" class="w-100 btn btn-lg btn-primary">Verify</button>
                        <div asp-validation-summary="ModelOnly" class="text-danger" role="alert"></div>
                    </form>
                </div>
            </div>
        </li>
    </ol>
</div>

@section Scripts {
    @await Html.PartialAsync("_ValidationScriptsPartial")
    <script src="~/lib/qrcode/qrcode.js"></script>
    <script type="text/javascript">

        new QRCode(document.getElementById("qrCode"),
            {
                text: "@Html.Raw(Model.AuthenticatorUri)",
                width: 200,
                height: 200
            });
    </script>
}

When we execute the program, a QR code will be generated in this View. Then you can set up two factor authentication using the Google authenticator with the help of this QR code. 

Step 3: Configure two-factor authentication 

Before running the application, we need to apply migrations to our app. Navigate to Tools >> NuGet Package Manager >> Package Manager Console. It will open the Package Manager Console. Put in the “Update-Database” command and hit Enter. This will update the database using Entity Framework Code First Migrations.

Run the application and click on “Register” in the top right corner of the homepage. You can see a user registration page. Fill in the details and click on the “Register” button as shown in the image below. 

Upon successful registration, you will be logged into the application and navigated to the home page. Here, you can see your registered Email id at the top right corner of the page. Click on it to navigate to the “Manage your account” page. Select “TwoFactorAuthentication” from the left menu. You will see a page similar to that shown below.  

 

 

Click on the “Set up authenticator app” button. You can see a QR code generated on your screen — it is asking for a “Verification Code”, also as shown in the image below. 

 

You need to install the Google Authenticator/Microsoft Authenticator app on your smartphone. It will allow you to scan this QR code in order to generate a Verification Code and complete a two-factor authentication setup. 

Open Microsoft Authenticator and click on verified IDs at the bottom. Click on “Scan a barcode” and scan the QR code generated by the web app. This will add a new account to Microsoft authenticator and generate a six-digit pin on your mobile screen. This is our two-factor authentication code. This is a TOTP ( time-based one-time password). You can observe that it keeps on changing frequently (life span of 30 seconds). 

Put this pin in the Verification Code textbox and click on verify. Upon successful verification, you will see a screen similar to the one shown below. This will give you the recovery codes for your account that will help to recover your account in case you are locked out. Take a note of these codes and keep them somewhere safe. 

 

Logout of the application and click on login again. Enter your registered email id and password and click on login. 

 

Now you can see a the two-factor authentication screen asking for the Authenticator code. Put in the code that is generated in your Google Authenticator app and click on Login. You will be successfully logged into the application and navigated to the home page. 

How to Setup Azure VM
Oct 10, 2024

What is Azure VM? Azure virtual machines (VMs) are a cloud-based computing service that allows users to run applications on the Microsoft Azure platform. VMs are a type of on-demand, scalable computing resource that offers a number of benefits, including:  Security: Azure VMs offer a secure way to run applications.  Affordability: Users can pay for extra VMs when needed and shut them down when not.  Flexibility: Users can choose from various operating systems, including Windows and Linux.  Scalability: Users can scale up to thousands of VMs based on demand or schedules.  Performance: Users can enhance network and storage performance with custom hardware.  Azure virtual machines (VMs) can be created through the Azure portal. This method provides a browser-based user interface to create VMs and their associated resources. In this blog, I'll show you how to use the Azure portal to deploy a virtual machine (VM) in Azure.   Sign in to the Azure portal. Create Virtual Machine Enter Virtual Machine in the search. Under Services, select Virtual machines. In the Virtual Machines page, select Create and then Azure virtual machine. The Create a Virtual Machine page opens. Under Project details, select the resource group. Under the instance details enter the Virtual machine name and choose "Windows Server 2022 Datacenter: Azure Edition - x64 Gen 2" for the Image. Leave the other defaults. Also use can choose image based on your requirement. Under Administrator account, provide a username, such as azureuser, and a password. Under Inbound port rules, choose Allow selected ports and then select RDP (3389) and HTTP (80) from the drop-down. Leave the remaining defaults and then select the Review + create button at the bottom of the page. After validation runs, select the Create button at the bottom of the page. After deployment is complete, select Go to resource. Connect to Virtual Machine On the overview page for your virtual machine, select Connect. Download the RDP file. Open the downloaded RDP file and click Connect when prompted. Click on more choise and enter your username and password that you have added while creating the VM and click on OK. You can see your VM is running now.     Here are some other things to know about Azure VMs:  Maintenance: Users still need to maintain the VM by configuring, patching, and installing software.  Cost: The cost of an Azure VM depends on the size and type of VM, as well as other services used with it.   Security: Users should take steps to ensure the security of their data and applications, such as identity management, encryption, and network protection.  Virtual machine selector: Users can use the virtual machine selector to find the right VMs for their needs and budget.    Conclusion: An Azure virtual machine gives you the flexibility of virtualization without buying and maintaining the physical hardware that runs it. However, you still need to maintain the virtual machine by performing tasks, such as configuring, patching, and installing the software that runs on it.

Serverless computing using Azure Function
Jul 17, 2024

Serverless computing is a widely adopted approach and an extension of the cloud computing model where customers can focus solely on building logic, with the server infrastructure being completely managed by third-party cloud service providers. In Microsoft Azure, serverless computing can be implemented in various ways, one of which is by using Azure Functions. In this blog, we will discuss how to use Azure Functions for serverless computing. Firstly, let us understand the following terms. What Is Serverless Computing? Serverless computing, also known as the Function-as-a-Service (FAAS) approach to building software applications, eliminates the need to manage the server hardware and software by the consumer and be taken care of by third-party vendors. What Are Azure Functions? Azure functions are the serverless solution that provides all the necessary resources to carry out the tasks with minimal lines of code, infrastructure, and cost. The Azure function are a combination of code and event allowing us to write the code in any language. A Step-by-Step Approach For Creating An Azure Function Go to the Azure portal, search for Function App, and select Function App. Create a new Function App and fill in the details accordingly. Basic tab You can select the Runtime stack and version based on your requirements. Here, I am selecting .NET with version 8 and the operating system Windows. Storage You may leave the default values or configure them according to your project requirements. The default values are configured as. Storage account: You may use the existing storage account or create a new account to store your function app. Monitoring Enable the Application insights to monitor the activity. Deployment tab To enable Continuous Integration and Continuous Deployment (CI/CD), you may connect your function app to a repository by authorizing it to GitHub. These are the important things to focus on while creating your function app, you may leave the remaining details as default or customize them according to your requirements. Once you finish configuring your app, you can click the “create” button at the bottom of the page.Now your app will start the process of deployment. Once deployment is done click on go to the resource tab and you will see your function app was created successfully. Now we need to create a function in our function app. As you can see We have various options to choose Visual Studio, VS code, and other editors or CLI. Choose an environment to create your function. I’ve chosen Visual Studio to create my function app. Create an Azure Functions with Visual Studio From the Visual Studio menu, select File > New > Project. In Create a new project, enter functions in the search box, choose the Azure Functions template, and then select Next. Here you can select the function based on your requirements. Here I am selecting Timer trigger function. Then click on the Create button to create a project. You will see that the default Timer trigger function is created. Here I have created one more function called "HTTPTrigger". Here, you can see two JSON files: host.json and local.settings.json. The local.settings.json file stores app settings and settings used by local development tools. Settings in the local.settings.json file are used only when you're running your project locally. When you publish your project to Azure, be sure to also add any required settings to the app settings for the function app. Publish to Azure Use the following steps to publish your project to a function app in Azure. In Solution Explorer, right-click the project and select Publish. In Target, select Azure then Next. Select Azure Function App (Windows) for the Specific target, which creates a function app that runs on Windows, and then select Next. In the Functions instance, You have to select the function that you created on the Azure portal and then click the finish button.  You can see that the publish profile has been added. Now, click on the Publish button to publish the function to Azure. Once the function is published, go to the Azure portal and search for Application Insights. You can find the Application Insights instance with the same name as the function. On the LHS, go to the Transaction search tab under Investigate and click on See all data in the last 24 hours. In the logs, you can see that your function is working properly. Conclusion In a nutshell, Azure functions provide a very precise environment for developers allowing them to more focus on coding rather than then managing infrastructure. This feature plays a key role in building scalable and responsive applications with low cost.

Comparison between Minimal APIs and Controllers
Jun 17, 2024

Introduction  In the ever-evolving landscape of web development, simplicity is key. Enter Minimal APIs in ASP.NET Core, a lightweight and streamlined approach to building web applications. In this detailed blog, we'll explore the concept of Minimal APIs, understand why they matter, and walk through their implementation in ASP.NET Core.    When to Use Minimal APIs?  Minimal APIs are well-suited for small to medium-sized projects, microservices, or scenarios where a lightweight and focused API is sufficient. They shine in cases where rapid development and minimal ceremony are top priorities.  You can find in this blog <link> how to create minimal api.  I am directly showing the comparison between MinimalAPI and controller.    Controllers: Structured and Versatile  Controllers, deeply rooted in the MVC pattern, have been a cornerstone of ASP.NET API development for years. They provide a structured way to organize endpoints, models, and business logic within dedicated controller classes.  Let's consider an example using Microsoft.AspNetCore.Mvc; namespace MinimalAPI.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet(Name = "GetWeatherForecast")] public IEnumerable<WeatherForecast> Get() { return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), TemperatureC = Random.Shared.Next(-20, 55), Summary = Summaries[Random.Shared.Next(Summaries.Length)] }) .ToArray(); } } } Advantages of Controllers in Action  Structure and Organization: Controllers offer a clear structure, separating concerns and enhancing maintainability.  Flexibility: They enable custom routes, complex request handling, and support various HTTP verbs.  Testing: Controllers facilitate unit testing of individual actions, promoting a test-driven approach   Minimal APIs: Concise and Swift  With the advent of .NET 6, Minimal APIs emerged as a lightweight alternative, aiming to minimize boilerplate code and simplify API creation.  Here's an example showcasing Minimal APIs.  using MinimalAPI; var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); var app = builder.Build(); app.MapGet("/GetWeatherForecast", () => { var rng = new Random(); var summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; var weatherForecasts = Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index).Date, TemperatureC = rng.Next(-20, 55), Summary = summaries[rng.Next(summaries.Length)] }).ToArray(); return Results.Ok(weatherForecasts); }); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run(); Advantages of Minimal APIs in Focus  Simplicity: Minimal APIs drastically reduce code complexity, ideal for smaller projects or rapid prototyping.  Ease of Use: They enable quick API creation with fewer dependencies, accelerating development cycles.  Potential Performance Boost: The reduced overhead might lead to improved performance, especially in smaller applications.    What you choose between MinimalAPI and Controller?  Choosing between Controllers and Minimal APIs hinges on various factors.  Project Scale: Controllers offer better organization and structure for larger projects with intricate architectures.  Development Speed: Minimal APIs shine when speed is crucial, suitable for rapid prototyping or smaller projects.  Team Expertise: Consider your team's familiarity with MVC patterns versus readiness to adopt Minimal APIs.    Conclusion  The decision between Controllers and Minimal APIs for .NET APIs isn't about one being superior to the other. Rather, it's about aligning the choice with the project's specific needs and constraints. Controllers offer robustness and versatility, perfect for larger, complex projects. On the other hand, Minimal APIs prioritize simplicity and rapid development, ideal for smaller, more straightforward endeavours. 

Meet Dobariya

About the Author

Meet Dobariya

Experienced .NET developer proficient in various technologies with a passion for continuous learning. Over 2 years of hands-on experience in software development across multiple domains. Enthusiastic about technology and adept at adapting to new challenges.