DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Working With dotConnect for Oracle in ASP.NET Core
  • GDPR Compliance With .NET: Securing Data the Right Way
  • In-App Browsers in Mobile Apps: Benefits, Challenges, Solutions
  • How to Enhance the Performance of .NET Core Applications for Large Responses

Trending

  • How to Use AWS Aurora Database for a Retail Point of Sale (POS) Transaction System
  • Bridging UI, DevOps, and AI: A Full-Stack Engineer’s Approach to Resilient Systems
  • Apache Spark 4.0: Transforming Big Data Analytics to the Next Level
  • How GitHub Copilot Helps You Write More Secure Code
  1. DZone
  2. Coding
  3. Frameworks
  4. ASP.NET Core Two Factor Authentication Using Google Authenticator

ASP.NET Core Two Factor Authentication Using Google Authenticator

Learn how to add an extra layer of security for your app's users by enabling two-factor authentication with ASP.NET Core.

By 
Ankit Sharma user avatar
Ankit Sharma
·
Apr. 03, 18 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
19.3K Views

Join the DZone community and get the full member experience.

Join For Free

In this article, we are going to learn how to perform two-factor authentication in an ASP.NET Core application using the Google Authenticator app. The user needs to configure the Google Authenticator app on his/her smartphone using the QR code generated in the web app. At the time of logging in to the web application, a user has to enter a six-digit pin that will be generated in the app to finish the two-factor authentication. The key generated in the app will be unique to the user id and is a time-based one-time password (TOTP); i.e., it will expire after a certain time.

Prerequisites

  • Install .NET Core 2.0.0 or above SDK from here.
  • Install the latest version of Visual Studio 2017 Community Edition from here.

Source Code

Before proceeding I would recommend you to get the source code from GitHub.

Create an MVC Web Application

Open Visual Studio and select File >> New >> Project. After selecting the project, a "New Project" dialog will open. Select .NET Core inside the Visual C# menu from the left panel. Then, select "ASP.NET Core Web Application" from the available project types. Set the name of the project as TwoFactAuth and press OK.

After clicking OK, a new dialog will open asking you to select the project template. You can observe two drop-down menus at the top left of the template window. Select ".NET Core" and "ASP.NET Core 2.0" from these drop-downs. Then, select "Web application (Model-View-Controller)" template. Click on the "Change Authentication" button; a "Change Authentication" dialog box will open. Select "Individual User Account" and click OK. Now, we need to click OK again to create our web app.

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 of your application. Now, your wwwroot folder will have the following structure.

Open 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 data-fr-src="~/lib/qrcodejs/qrcode.js"></script>  
    <script type="text/javascript">  
        new QRCode(document.getElementById("qrCode"),  
            {  
                text: "@Html.Raw(Model.AuthenticatorUri)",  
                width: 200,  
                height: 200  
            });  
    </script>  
}

This EnableAuthenticator.cshtml file already has a div with an id of "qrCode" (see line 25 in below code). 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 the form of width and height.

So, finally, your EnableAuthenticator.cshtml  file will look like this.

@model EnableAuthenticatorViewModel  
@{  
    ViewData["Title"] = "Enable authenticator";  
    ViewData.AddActivePage(ManageNavPages.TwoFactorAuthentication);  
}  

<h4>@ViewData["Title"]</h4>  
<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=825071">Windows Phone</a>,  
                <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&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">To enable QR code generation please read our <a href="https://go.microsoft.com/fwlink/?Linkid=852423">documentation</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 method="post">  
                        <div class="form-group">  
                            <label asp-for="Code" class="control-label">Verification Code</label>  
                            <input asp-for="Code" class="form-control" autocomplete="off" />  
                            <span asp-validation-for="Code" class="text-danger"></span>  
                        </div>  
                        <button type="submit" class="btn btn-default">Verify</button>  
                        <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
                    </form>  
                </div>  
            </div>  
        </li>  
    </ol>  
</div>  
@section Scripts {  
    @await Html.PartialAsync("_ValidationScriptsPartial")  
    <script src="~/lib/qrcodejs/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 and the user can set up two-factor authentication using Google authenticator with the help of this QR code.

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.

Press F5 to launch 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 taken 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 lefthand menu. You can see a page similar to that shown below.

Click on the Configure authenticator app button. You can see a QR code generated on your screen and it is asking for a Verification Code as shown in the image below.

You need to install the Google Authenticator app on your smartphone to scan this QR code in order to generate a Verification Code and complete the two-factor authentication setup. Download and install Google authenticator for Android from the Play Store and for iOS from the App Store. I am using an Android device for this demo.

Launch the app on your smartphone. You can see the welcome screen as shown in the image below.

Click on "Begin." It will ask you to add an account by providing two options:

  1. Scan a barcode.

  2. Enter a provided key.

Click on "Scan a barcode" and scan the QR code generated by the web app. This will add a new account to Google 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 (lifespan of 30 seconds).

Here you can also see the application name as well as your registered email id in the app as shown below.

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 it safe with you.

And thus, the two-factor authentication setup is complete. Let's check if our two-factor authentication is working correctly or not.

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 Authenticator code. Put in the code that is generated currently in your Google Authenticator app and click on Login. You will be successfully logged into the application and navigated to the home page.

If you check "Remember this machine" option then it will not ask for the Authenticator code  on the same machine again. You can skip the two-factor authentication in this case.

See Also

  • Cookie Authentication With ASP.NET Core 2.0
  • Authentication Using Facebook In ASP.NET Core 2.0
  • Authentication Using LinkedIn In ASP.NET Core 2.0 

Conclusion

We have successfully generated a QR code using the qrcode.js JavaScript library and used it to configure Google Authenticator. This app will generate a six-digit TOTP which the user needs to enter while logging in to the web application, thus implementing two-factor authentication in an ASP.NET Core application.

You can check my other articles on ASP .NET Core here.

ASP.NET Google Authenticator ASP.NET Core authentication Google (verb) mobile app QR code .NET

Published at DZone with permission of Ankit Sharma, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Working With dotConnect for Oracle in ASP.NET Core
  • GDPR Compliance With .NET: Securing Data the Right Way
  • In-App Browsers in Mobile Apps: Benefits, Challenges, Solutions
  • How to Enhance the Performance of .NET Core Applications for Large Responses

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!