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

如何使用Google Authenticator在ASP.NET Core中设置两因素身份验证相关推荐

  1. laravel集成谷歌验证_如何将Google的两因素身份验证添加到Laravel

    laravel集成谷歌验证 Laravel is a wonderful PHP framework that makes building applications with PHP a lot o ...

  2. Google Authenticator:将其与您自己的Java身份验证服务器配合使用

    用于移动设备的Google Authenticator应用程序是一个非常方便的应用程序,它实现了TOTP算法(在RFC 6238中指定). 使用Google Authenticator,您可以生成时间 ...

  3. ASP.NET Core 中的 User Agent 识别及搜索引擎爬虫鉴定方法

    User Agent中文名为用户代理,简称 UA,它是一个特殊字符串头,使得服务器能够识别客户使用的操作系统及版本.CPU 类型.浏览器及版本.浏览器渲染引擎.浏览器语言.浏览器插件等. 百度百科 在 ...

  4. 在ASP.NET Core中使用brotli压缩

    Brotli是一种全新的数据格式,可以提供比Zopfli高20-26%的压缩比.据谷歌研究,Brotli压缩速度同zlib的Deflate实现大致相同,而在Canterbury语料库上的压缩密度比LZ ...

  5. 如何使用C#在ASP.NET Core中轻松实现QRCoder

    by Yogi 由瑜伽士 如何使用C#在ASP.NET Core中轻松实现QRCoder (How to easily implement QRCoder in ASP.NET Core using ...

  6. asp.net core中IHttpContextAccessor和HttpContextAccessor的妙用

    分享一篇文章,关于asp.net core中httpcontext的拓展. 现在,试图围绕HttpContext.Current构建你的代码真的不是一个好主意,但是我想如果你正在迁移一个企业类型的应用 ...

  7. asp绑定gridview属性_理解ASP.NET Core中的模型验证

    当MVC执行模型绑定后,为了验证绑定为参数提供的值是否符合预期,还需要进行模型验证. 一.理解模型验证 模型验证是指模型绑定后对Action参数进行验证的过程.它会根据事先定义的规则对参数的值进行验证 ...

  8. 在asp.net core中使用托管服务实现后台任务

    在业务场景中经常需要后台服务不停的或定时处理一些任务,这些任务是不需要及时响应请求的. 在 asp.net中会使用windows服务来处理. 在 asp.net core中,可以使用托管服务来实现,托 ...

  9. ASP.NET Core中显示自定义错误页面-增强版

    之前的博文 ASP.NET Core中显示自定义错误页面 中的方法是在项目中硬编码实现的,当有多个项目时,就会造成不同项目之间的重复代码,不可取. 在这篇博文中改用middleware实现,并且放在独 ...

最新文章

  1. Android获取手机应用程序包的信息
  2. 计算网络经典书籍--计算机网络:自顶向下方法
  3. 10 个冷门但又非常实用的 Docker 使用技巧
  4. jquery 插件和后台模板搜集
  5. 万能监控摄像头app软件下载_黄岩安科瑞环保设备用电监控app下载
  6. .NET基础 (03)生成、部署和管理
  7. 使用awk取passwd10-20行然后重定向
  8. -9 逆序输出一个整数的各位数字_【Java编程基本功】(八)逆序输出、是否为回文数,判断星期几,升序排列...
  9. java版AES加密算法实现
  10. 谷歌浏览器无法上网问题解决
  11. 解决微信设置字体大小对 rem 适配方式的影响
  12. 哪吒故里之争:讲好地方故事,真这么难?
  13. 关于汉庭连锁酒店加盟的4个优势
  14. android 载入svg动画,Android 加载SVG动画
  15. Unity Live2D 通过脚本播放动画 Motion Controller 学习使用
  16. java与c的交互,java与c/c++之间的数据交互,java交互
  17. Flutter学习之入门和体验
  18. 在地址栏显示网站的图标
  19. 牢记卖股票的四大纪律十项注意
  20. civil纵断面如何显示竖向转角?

热门文章

  1. readonly的用法
  2. (转)Java中的守护线程
  3. 使用Nginx+uWSGI部署Django项目
  4. django入门记录 2
  5. 纯脚本创建桌面快捷方式
  6. 《活出生命的意义》:人生有何意义?
  7. dataTables本地刷新数据解决只能初始化一次问题
  8. php中Session的生成机制、回收机制和存储机制探究
  9. C#实现简单的 Ping 的功能,用于测试网络是否已经联通
  10. 采购订单单价金额屏蔽