如何使用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.mzph.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/…