如何使用Google Authenticator在ASP.NET Core中設置兩因素身份驗證

介紹 (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:

點擊“開始”。 它將要求您通過提供兩個選項來添加帳戶:

  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 (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/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/394299.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/394299.shtml
英文地址,請注明出處:http://en.pswp.cn/news/394299.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

280. Wiggle Sort

最后更新 二刷 這個題做得真蠢。上來想的復雜了&#xff0c;想的是quick sort之類的&#xff0c;然后一個一個交換。 實際上直接交換就行。。沒啥特別的。 回頭看一刷也是同樣的思考過程 宿命論啊。。 Time: O(n) Space: O(1) public class Solution {public void wiggleSort(i…

避免人為災難:盤點數據中心里十大愚蠢行為

對于企業運營&#xff0c;數據中心從設計、部署等各個環節都有極其嚴格的規范&#xff0c;保證簡單的“題目”不出錯也需要企業IT管理人員的智慧&#xff0c;在數據中心任何一個小錯誤往往會帶來巨大災難。數據中心從設計、部署、測試、運行、運維等各個環節都不能有任何的疏忽…

python中node.tag的用法_python在ui自動化中的一些常見用法

http://cn.python-requests.org/zh_CN/latest 可以查看requests庫的說明&#xff0c;pprint(res.json(),width30)可以對請求的返回值按照json格式化形式進行打印。常見的content-type 有application/x-www-form-urlencoded、application/json、application/xml。自動化測試操作…

leetcode1039. 多邊形三角剖分的最低得分(動態規劃)

給定 N&#xff0c;想象一個凸 N 邊多邊形&#xff0c;其頂點按順時針順序依次標記為 A[0], A[i], …, A[N-1]。 假設您將多邊形剖分為 N-2 個三角形。對于每個三角形&#xff0c;該三角形的值是頂點標記的乘積&#xff0c;三角剖分的分數是進行三角剖分后所有 N-2 個三角形的…

TRIZ解決問題方法

個人覺的成功是有規律的&#xff0c;那些成功的人士&#xff0c;都有一套處理事情的秘籍。只要我們的思維方式把那些秘籍融會貫通&#xff0c;并快速執行&#xff0c;我們有一天也會成功的。 TRIZ解決問題的5點方法。 1.確定最終目標。 2.列出阻礙因素 3.消除阻礙因素 4.可以利…

windows調用python_windows 快捷調用Python語言

本文主要向大家介紹了windows 快捷調用Python語言&#xff0c;通過具體的內容向大家展示&#xff0c;希望對大家學習Python語言有所幫助。場景1&#xff1a;某云平臺的賬號/或密碼比較長&#xff0c;一旦瀏覽器緩存失效&#xff0c;就要去郵件/文件查找&#xff0c;費時費力場景…

《量化投資:以MATLAB為工具》連載(1)基礎篇-N分鐘學會MATLAB(上)

http://blog.sina.com.cn/s/blog_4cf8aad30102uylf.html 《量化投資&#xff1a;以MATLAB為工具》連載(1)基礎篇-N分鐘學會MATLAB&#xff08;上&#xff09; 《量化投資&#xff1a;以MATLAB為工具》簡介 《量化投資&#xff1a;以MATLAB為工具》是由電子工業出版社&#xff0…

android-開源項目_我如何擺脫對開源的恐懼,并開始了自己的項目-以及如何做到。...

android-開源項目by Linea Brink Andersen通過Linea Brink Andersen 我如何擺脫對開源的恐懼&#xff0c;并開始了自己的項目-以及如何做到。 (How I crushed my fear of open source and started my own project — and how you can, too.) A week ago, I started an Open So…

本題要求實現函數輸出n行數字金字塔。_練習5-3 數字金字塔 (15分)

本題要求實現函數輸出n行數字金字塔。函數接口定義&#xff1a;void pyramid( int n );其中n是用戶傳入的參數&#xff0c;為[1, 9]的正整數。要求函數按照如樣例所示的格式打印出n行數字金字塔。注意每個數字后面跟一個空格。裁判測試程序樣例&#xff1a;#include <stdio.…

leetcode167. 兩數之和 II - 輸入有序數組(二分查找)

給定一個已按照升序排列 的有序數組&#xff0c;找到兩個數使得它們相加之和等于目標數。 函數應該返回這兩個下標值 index1 和 index2&#xff0c;其中 index1 必須小于 index2。 說明: 返回的下標值&#xff08;index1 和 index2&#xff09;不是從零開始的。 你可以假設每…

thinkcmf 橫向排列數據_利用python進行數據分析之數據清洗規整

1.處理缺失值數據使用dropna()時&#xff0c;注意里面參數axis、how、thresh的用法使用fillna()時&#xff0c;注意里面參數value、method、inplace、limit的用法2.數據轉換去重data.drop_duplicates(keeplast)#注意keep的用法映射map&#xff08;&#xff09;針對的是一維數組…

v$asm_diskgroup中state的說明

1.使用oracle賬號連接數據庫&#xff0c;查看v$asm_diskgroup 2.使用grid賬號連接ASM實例&#xff0c;查看v$asm_diskgroup 3.官方v$asm_diskgroup關于state的解釋 https://docs.oracle.com/en/database/oracle/oracle-database/19/refrn/V-ASM_DISKGROUP.html#GUID-5CF77719-7…

AutoMapper的介紹與使用(二)

AutoMapper的匹配 1&#xff0c;智能匹配 AutoMapper能夠自動識別和匹配大部分對象屬性: 如果源類和目標類的屬性名稱相同&#xff0c;直接匹配&#xff0c;不區分大小寫目標類型的CustomerName可以匹配源類型的Customer.Name目標類型的Total可以匹配源類型的GetTotal()方法…

站長快訊 WordPress跨站攻擊漏洞修補

WordPress中發現一些漏洞&#xff0c;攻擊者利用該漏洞可以發起跨站腳本攻擊&#xff0c;繞過WordPress安全性限制&#xff0c;獲取較為敏感的修訂歷史記錄的信息&#xff0c;或者綁架站點以用于DDoS攻擊。 CVE ID CVE-2015-8834 CVE-2016-5832 CVE-2016-5834 CVE-2016-5835 C…

暢通無阻的公式:乘員組從幾乎破產變成了吸引500萬游客的方式

How could you go from almost no traction and running out of money, to getting millions of visitors to your website?您怎么能從幾乎沒有牽引力和資金用盡的角度&#xff0c;如何吸引數百萬的網站訪問者&#xff1f; You could do like Crew accidentally did with Uns…

leetcode1302. 層數最深葉子節點的和(深度優先搜索)

給你一棵二叉樹&#xff0c;請你返回層數最深的葉子節點的和。 代碼 class Solution {int[] depthnew int[]{Integer.MIN_VALUE,0};//記錄最深層數和對應的和public int deepestLeavesSum(TreeNode root) {if(rootnull) return 0;deep(root,0);return depth[1];}public void d…

Python筆記 【無序】 【五】

描述符 將某種特殊類型的類【只要實現了以下或其中一個】的實例指派給另一個類的屬性 1.__get__(self,instance,owner)//訪問屬性&#xff0c;返回屬性的值 2.__set__(self,instance,value)//將在屬性分配【即賦值】中調用&#xff0c;不返回任何內容 3.__delete__&#xff08;…

化工圖紙中LISP_化工設備廠參展模型設計制作

最近這個案子是受某化工設備企業委托做四套設備模型 用來參加展會在模型制作過程中&#xff0c;這類案例經常遇到。但是客戶所提供的CAD圖紙&#xff0c;往往是實物尺寸在進行縮放的過程中常會造成過薄和過于精細的情況出現眼下技術小哥就遇到這類情況讓我們先看看客戶提供的C…

社交大佬們的數據“大”在哪里?

文章講的是社交大佬們的數據“大”在哪里&#xff0c;“別說忙&#xff0c;沒工夫看書&#xff0c;你那刷FB/朋友圈的工夫騰出來&#xff0c;保證每周啃下一本”&#xff0c;小編身邊總充斥著這樣的“訓話”。 額&#xff0c;奈何我每天的工作離不開從社交媒體中獲取信息&#…

微信支付JsAPI

https://pay.weixin.qq.com/wiki/doc/api/download/WxpayAPI_php_v3.zip 下載獲取微信支付demo壓縮包打開壓縮包&#xff0c;并將其中 WxpayAPI_php_v3\example下的 jsapi.php log.php WxPay.JsApiPay.php WxPay.MicroPay.php WxPay.NativePay.php 解壓縮到根目錄 tellingtent/…