介紹 (Introduction)
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.
在本文中,我們將學習如何使用Google Authenticator應用程序在ASP.NET Core應用程序中執行兩因素身份驗證。
To use it, you need to configure the Google Authenticator app on your smartphone using the QR code generated in the web app. When you login to the web application, you have 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 your userID, and is a time-based one-time password (TOTP) — that is, it will expire after a certain time.
要使用它,您需要使用網絡應用程序中生成的QR碼在智能手機上配置Google Authenticator應用程序。 登錄Web應用程序時,您必須輸入一個將在應用程序中生成的六位數密碼,以完成兩因素身份驗證。 應用程序中生成的密鑰對于您的用戶ID是唯一的,并且是基于時間的一次性密碼(TOTP),也就是說,它將在特定時間后失效。
先決條件 (Prerequisites)
Install .NET Core 2.0.0 or above SDK from here.
從此處安裝.NET Core 2.0.0或更高版本的SDK。
Install the latest version of Visual Studio 2017 Community Edition from here.
從此處安裝最新版本的Visual Studio 2017社區版。
源代碼 (Source Code)
Before proceeding, I would recommend that you get the source code from GitHub
在繼續之前,我建議您從GitHub獲取源代碼。
創建MVC Web應用程序 (Create the 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. Name the project “TwoFactAuth” and press OK.
打開Visual Studio,然后選擇“文件>>新建>>項目”。 選擇項目后,將打開“新建項目”對話框。 從左側面板的Visual C#菜單中選擇.NET Core。 然后,從可用的項目類型中選擇“ ASP.NET Core Web應用程序”。 將項目命名為“ TwoFactAuth”,然后按OK。
After clicking OK, a new dialog will open asking you to select the project template. You can see 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 the “Web application (Model-View-Controller)” template. Click on “Change Authentication” button. A “Change Authentication” dialog box will open. Select “Individual User Account” and click OK. Now, click OK again to create your web app.
單擊確定后,將打開一個新對話框,要求您選擇項目模板。 您可以在模板窗口的左上方看到兩個下拉菜單。 從這些下拉列表中選擇“ .NET Core”和“ ASP.NET Core 2.0”。 然后,選擇“ Web應用程序(模型-視圖-控制器)”模板。 點擊“更改身份驗證”按鈕。 將打開“更改身份驗證”對話框。 選擇“個人用戶帳戶”,然后單擊“確定”。 現在,再次單擊“確定”以創建您的Web應用程序。
添加QR碼以配置兩因素身份驗證 (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.
我們將使用QR碼來配置Google身份驗證器應用程序并將其與我們的網絡應用程序同步。 從https://davidshimjs.github.io/qrcodejs/下載qrcode.js JavaScript庫,并將其放入應用程序的“ wwwroot \ lib”文件夾中。 現在,“ wwwroot”文件夾將具有以下結構。
Open the “Views\Manage\EnableAuthenticator.cshtml” file. You will find @section Scripts at the end of the file. Put the following code in it.
打開“ Views \ Manage \ EnableAuthenticator.cshtml” 文件。 您將在文件末尾找到@section腳本 。 將以下代碼放入其中。
@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> }
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.
這個“ EnableAuthenticator.cshtml” 文件已經有一個ID為“ qrCode”的div(請參見下面的代碼段)。 我們正在使用qrcode.js庫在該div中生成QR碼。 我們還根據寬度和高度來定義QR碼的尺寸。
So finally, your “EnableAuthenticator.cshtml” file will look like this.
所以最后,您的“ EnableAuthenticator.cshtml” 文件將如下所示。
@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. Then you can set up two factor authentication using the Google authenticator with the help of this QR code.
當我們執行程序時,將在此視圖中生成QR碼。 然后,您可以在此QR碼的幫助下使用Google身份驗證器設置兩因素身份驗證。
配置兩因素身份驗證 (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.
在運行應用程序之前,我們需要將遷移應用到我們的應用程序。 導航到工具>> NuGet軟件包管理器>>軟件包管理器控制臺。 它將打開軟件包管理器控制臺。 放入“ Update-Database”命令,然后按Enter。 這將使用實體框架代碼優先遷移來更新數據庫。
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.
按F5啟動應用程序,然后單擊主頁右上角的“注冊”。 您可以看到一個用戶注冊頁面。 填寫詳細信息,然后單擊“注冊”按鈕,如下圖所示。
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.
成功注冊后,您將登錄到該應用程序并導航至主頁。 在這里,您可以在頁面的右上角看到注冊的電子郵件ID。 單擊它以導航到“管理您的帳戶”頁面。 從左側菜單中選擇“ TwoFactorAuthentication”。 您將看到類似于以下內容的頁面。
Click on the “Configure 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.
單擊“配置身份驗證器應用程序”按鈕。 您可以在屏幕上看到生成的QR碼-要求輸入“驗證碼”,也如下圖所示。
You need to install the Google Authenticator app on your smartphone. It will allow you to scan this QR code in order to generate a Verification Code and complete two-factor authentication setup.
您需要在智能手機上安裝Google Authenticator應用。 它將允許您掃描此QR碼以生成驗證碼并完成兩因素身份驗證設置。
Download and install Google authenticator from the Play Store for Android and from the App Store for iOS. We are using an Android device for this demo.
從Android的Play商店和iOS的App Store下載并安裝Google身份驗證器。 我們正在使用Android設備進行此演示。
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:
點擊“開始”。 它將要求您通過提供兩個選項來添加帳戶:
- Scan a barcode 掃描條形碼
- 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 (life span of 30 seconds).
單擊“掃描條形碼”,然后掃描由Web應用程序生成的QR碼。 這會將新帳戶添加到Google身份驗證器,并在您的手機屏幕上生成一個六位數的密碼。 這是我們的兩因素身份驗證代碼。 這是TOTP(基于時間的一次性密碼)。 您可以觀察到它不斷變化(壽命為30秒)。
Now you can see the application name as well as your registered email id in the app, as shown below.
現在,您可以在應用程序中看到應用程序名稱以及您注冊的電子郵件ID,如下所示。
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.
將此圖釘放在驗證碼中 文本框,然后單擊驗證。 驗證成功后,您將看到類似于以下所示的屏幕。 這將為您提供帳戶的恢復代碼,以在您被鎖定時幫助您恢復帳戶。 記下這些代碼,并將其放在安全的地方。
And thus, the two-factor authentication setup is complete. Let’s check if our two-factor authentication is working correctly or not.
至此,兩因素驗證設置完成。 讓我們檢查我們的兩因素身份驗證是否正常工作。
執行演示 (Execution Demo)
Logout of the application and click on login again. Enter your registered email id and password and click on login.
注銷該應用程序,然后再次單擊登錄。 輸入您的注冊電子郵件ID和密碼,然后單擊登錄。
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.
現在,您將看到一個兩要素身份驗證屏幕,詢問身份驗證器代碼。 輸入您在Google Authenticator應用程序中生成的代碼,然后單擊“登錄”。 您將成功登錄到應用程序并導航到主頁。
If you check the “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.
如果您選中“記住這臺機器”選項,則它將不要求提供Authenticator代碼 在同一臺機器上。 在這種情況下,您可以跳過兩因素身份驗證。
結論 (Conclusion)
We have successfully generated a QR code using the qrcode.js JavaScript library and used it to configure the Google Authenticator app. This app will generate a six-digit TOTP which you need to enter when logging in to the web application. This implements two-factor authentication in a ASP.NET Core application.
我們已經使用qrcode.js JavaScript庫成功生成了QR碼,并將其用于配置Google Authenticator應用。 該應用程序將生成一個六位數的TOTP,您需要在登錄Web應用程序時輸入該值。 這將在ASP.NET Core應用程序中實現兩因素身份驗證。
You can also find this article at C# Corner.
您也可以在C#Corner上找到此文章。
You can check out my other articles on ASP .NET Core here.
您可以在此處查看有關ASP.NET Core的其他文章。
也可以看看 (See Also)
Cookie Authentication With ASP.NET Core 2.0
使用ASP.NET Core 2.0進行Cookie身份驗證
Authentication Using Facebook In ASP.NET Core 2.0
在ASP.NET Core 2.0中使用Facebook進行身份驗證
Authentication Using Google In ASP.NET Core 2.0
在ASP.NET Core 2.0中使用Google進行身份驗證
Authentication Using Twitter In ASP.NET Core 2.0
在ASP.NET Core 2.0中使用Twitter進行身份驗證
Authentication Using LinkedIn In ASP.NET Core 2.0
在ASP.NET Core 2.0中使用LinkedIn進行身份驗證
Originally published at https://ankitsharmablogs.com/
最初發表于 https://ankitsharmablogs.com/
翻譯自: https://www.freecodecamp.org/news/how-to-set-up-two-factor-authentication-on-asp-net-core-using-google-authenticator-4b15d0698ec9/