html - 我可以在移动浏览器上自动读取 OTP 吗?
问题描述
我正在研究在移动浏览器上自动读取登录 OTP。我的 Web 应用程序是用 Angular 7 构建的。
一旦用户点击登录,就会通过 AWS 向用户的手机发送一个带有 6 位数代码的 OTP。
我查看了 Google 的 SMS Retriever API,但对我的情况没有帮助。
是否可以从移动浏览器读取 OTP?
解决方案
这是一个老问题,在发布问题的时候,它是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 JavaScript 和 Web 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
它正式启动。但是,许多改进仍在进行中。
推荐阅读
- java - “预期标识符”如何解决以及将其保留在方法中是什么意思
- excel - 1004 未找到单元格 - 错误处理
- pytorch - Pytorch 中的简单数据召回 RNN
- javascript - 淘汰赛 JS - 承诺递归
- angular - 带有吸气剂的 Angular v2+ 打字稿深拷贝/克隆
- python - WSGI Python3 和 Apache Lounge - 您无权访问此服务器上的 /wsgi
- python - 单个值的迭代与包含它的列表或元组完全一样
- mongodb - 将数据存储为地图而不是数组以用于 embedMany 关系
- tensorflow - 用于训练具有对比损失的排名模型的批处理结构?
- c# - 为什么我的代码在 C# 中使用第二个鼠标按钮失败?