启用在 ASP.NET Core TOTP 身份验证器应用的 QR 代码生成Enable QR Code generation for TOTP authenticator apps in ASP.NET Core

本文内容

QR 码需要 ASP.NET Core 2.0 或更高版本。

ASP.NET Core 附带的单个身份验证的身份验证器应用程序的支持。两个身份验证 (2FA) 身份验证器应用程序,使用基于时间的一次性密码算法 (TOTP),是推荐的方法用于 2FA 的行业。2FA 使用 TOTP 优于 SMS 2FA。验证器应用提供6到8位的数字代码,用户在确认其用户名和密码后必须输入。通常会在智能手机上安装验证器应用。

ASP.NET Core web 应用程序模板支持身份验证器,但不提供对 QRCode 生成的支持。QRCode 生成器简化了2FA 的设置。本文档将指导你完成将QR 代码生成添加到 "2FA" 配置页的步骤。

使用外部身份验证提供程序(如GoogleFacebook)不会进行双重身份验证。外部登录名受外部登录提供程序所提供的任何机制的保护。例如,请考虑Microsoft身份验证提供程序需要硬件密钥或其他2FA 方法。如果默认模板强制实施了 "本地" 2FA,则用户需要满足两种2FA 方法,这并不是一种常用方案。

将 QR 代码添加到 "2FA" 配置页Adding QR Codes to the 2FA configuration page

这些说明使用 https://davidshimjs.github.io/qrcodejs/ 存储库中的qrcode

  • 按照基架标识中的说明生成 /Areas/Identity/Pages/Account/Manage/EnableAuthenticator.cshtml
  • /Areas/Identity/Pages/Account/Manage/EnableAuthenticator.cshtml中,找到文件末尾的 Scripts 部分:
  • 页面/帐户/管理/EnableAuthenticator (Razor Pages)或视图/管理/EnableAuthenticator (MVC)中,找到文件末尾的 Scripts 部分:
  1. @section Scripts {
  2. @await Html.PartialAsync("_ValidationScriptsPartial")
  3. }
  • 更新 Scripts 部分,以添加对添加的 qrcodejs 库的引用,并调用以生成 QR 代码。其外观应如下所示:
  1. @section Scripts {
  2. @await Html.PartialAsync("_ValidationScriptsPartial")
  3. <script type="text/javascript" src="~/lib/qrcode.js"></script>
  4. <script type="text/javascript">
  5. new QRCode(document.getElementById("qrCode"),
  6. {
  7. text: "@Html.Raw(Model.AuthenticatorUri)",
  8. width: 150,
  9. height: 150
  10. });
  11. </script>
  12. }
  • 删除链接到这些说明的段落。

运行你的应用,并确保你可以扫描 QR 代码并验证验证器证明的代码。

更改 QR 码中的站点名称Change the site name in the QR Code

QR 代码中的站点名称取自最初创建项目时选择的项目名称。可以通过在 /Areas/Identity/Pages/Account/Manage/EnableAuthenticator.cshtml.cs中查找 GenerateQrCodeUri(string email, string unformattedKey) 方法来更改该方法。

QR 代码中的站点名称取自最初创建项目时选择的项目名称。您可以通过在页面/帐户/管理/EnableAuthenticator (Razor Pages)文件或控制器/ManageController (MVC)文件中查找 GenerateQrCodeUri(string email, string unformattedKey) 方法来更改它。

模板中的默认代码如下所示:

  1. private string GenerateQrCodeUri(string email, string unformattedKey)
  2. {
  3. return string.Format(
  4. AuthenticatorUriFormat,
  5. _urlEncoder.Encode("Razor Pages"),
  6. _urlEncoder.Encode(email),
  7. unformattedKey);
  8. }

调用 string.Format 的第二个参数是你的站点名称,从你的解决方案名称获取。可以将其更改为任何值,但必须始终以 URL 编码。

使用其他 QR 码库Using a different QR Code library

可以将 QR 代码库替换为首选库。HTML 包含一个 qrCode 元素,你可以在其中放置 QR 码,方法是库提供的任何机制。

可以在中找到 QR 码的格式正确的 URL:

  • 模型的 AuthenticatorUri 属性。
  • qrCodeData 元素中的 data-url 属性。

TOTP 客户端和服务器时间偏差TOTP client and server time skew

TOTP (基于时间的一次性密码)身份验证取决于服务器和验证器设备的时间是否准确。标记只持续30秒。如果 TOTP 2FA 登录失败,请检查服务器时间是否准确,并最好是同步到准确的 NTP 服务。