首页 > 解决方案 > 我可以在移动浏览器上自动读取 OTP 吗?

问题描述

我正在研究在移动浏览器上自动读取登录 OTP。我的 Web 应用程序是用 Angular 7 构建的。

一旦用户点击登录,就会通过 AWS 向用户的手机发送一个带有 6 位数代码的 OTP。

我查看了 Google 的 SMS Retriever API,但对我的情况没有帮助。

是否可以从移动浏览器读取 OTP?

标签: htmlangulartypescriptone-time-password

解决方案


这是一个老问题,在发布问题的时候,它是not possible

但现在我们可以OTP移动浏览器上阅读。

使用WEBOTP API ,我们可以检测网络上移动设备的 OTP 。

您可以使用以下代码检查这是否适用于您的浏览器

if (!window.OTPCredential) {
  console.log('Feature Not Available');
}
else{
  console.log('Feature Available');
}

注意:如果您在笔记本电脑或台式机上进行测试,那么上面的代码将为您提供 Feature Not Available。要在笔记本电脑或台式机上进行测试,您需要将切换开关更改为移动设备。

SMS Receiver API JavaScriptWeb OTP API W3C 社区

您可以在上述链接中获取文档。

在使用之前OTPCredential,我们需要在一段时间后AbortController使用哪个来禁用WebOTP API(自动阅读短信)(可以基于时间或在阅读短信后)。

 const ac = new AbortController();
 setTimeout(() => {
   ac.abort();
 }, 1 * 60 * 1000);

在上述代码中, WebOTP API将在 1 分钟后终止。

您可以拥有这种类型的 HTML 表单

<form action="/verify-otp" method="POST">
  <input type="text"
         inputmode="numeric"
         autocomplete="one-time-code"
         pattern="\d{6}"
         required>
</form>

现在,用户将在其移动设备上接收的 SMS 格式如下。

@BOUND_DOMAIN #OTP_CODE

其中上述行可以是您短信的最后一行

  • @BOUND_DOMAIN将您的网站域如@www.examle.com
  • #OTP_CODE将是用于身份验证的 OTP,例如 #1234(仅保留 4 到 6 位数字。)

因此 SMS 格式将是这样的:

Hi User, please do not share your OTP with anyone.
@www.example.com #123456

要调用WebOTP API,我们需要知道Web Authentication API

 navigator.credentials.get([options])

调用WebOTP API需要上述代码

 navigator.credentials.get({
      otp: { transport:['sms'] },
      signal: ac.signal //This is from the AbortController
 }).then(otp => {
      input.value = otp.code;
      // Automatically submit the form when an OTP is obtained.
 }).catch(err => {
      console.log(err);
});

现在,下面是演示代码

HTML 代码:

<form action="/verify-otp" method="POST">
  <input type="text"
         inputmode="numeric"
         autocomplete="one-time-code"
         pattern="\d{6}"
         required>
</form>

JavaScript 代码:

if ('OTPCredential' in window) {
  window.addEventListener('DOMContentLoaded', e => {
    const input = document.querySelector('input[autocomplete="one-time-code"]');
    if (!input) return;
    // Cancel the Web OTP API if the form is submitted manually.
    const ac = new AbortController();
    const form = input.closest('form');
    if (form) {
      form.addEventListener('submit', e => {
        // Cancel the Web OTP API.
        ac.abort();
      });
    }
    // Invoke the Web OTP API
    navigator.credentials.get({
      otp: { transport:['sms'] },
      signal: ac.signal
    }).then(otp => {
      input.value = otp.code;
      // Automatically submit the form when an OTP is obtained.
      if (form) form.submit();
    }).catch(err => {
      console.log(err);
    });
  });
}

短信格式可能是这样的:

Hi, this is a demo OTP
@www.mydomain.com #1234



OYO(There Tech Blog)等公司使用此功能。

注意-截至目前,它处于开发阶段,可从Chrome 78


UPDATE 2020
Chrome 84它正式启动。但是,许多改进仍在进行中。


推荐阅读