Help users with OTPs received via SMS
Updated
¿Qué es la API from Web OTP?
En estos días, la mayoría de las persons en el mundo poseen un dispositivo móvil y los desarrolladores suelen usar números de teléfono como identificador para los usuarios de sus servicios.
Hay una variedad de formas de verificar los números de teléfono, pero una contraseña de un solo uso (OTP) generada aleatoriamente enviada por SMS es una de las más comunes. Enviar este código de vuelta al server del desarrollador demuestra el control del número de teléfono.
The Web OTP API was originally called the SMS Receiver API. You may still see it by that name in some places. If you used that API, you should still read this article. There are significant differences between the current and previous versions of the API.
This idea is already implemented in many scenarios to achieve:
- Número de teléfono como identificador del Username. When signing up for a new service, some websites ask for a phone number instead of an email address and use it as an account identifier.
- Two-step verification. When you log in, a website asks for a one-time code sent by SMS in addition to a password or other knowledge factor for added security.
- Payment confirmation. When a user makes a payment, requesting a unique code sent via SMS can help verify the person's intent.
El proceso actual crea fricciones para los usuarios. Encontrar una OTP dentro de un mensaje SMS, luego copiarlo y pegarlo en el formulario es engorroso, lo que reduce las tasas de conversion en los recorridos críticos del usuario. Aliviar esto ha sido una solicitud de muchos de los desarrolladores globales más importantes para la web. Android tiene an API that does exactly this. It also does
ios
and
Safari.
La API Web OTP permite que su aplicación reciba mensajes con formato especial vinculados al origen de su aplicación. A partir de esto, puede obtener una OTP mediante programming a partir de un mensaje SMS y verificar un número de teléfono para el usuario más fácilmente.
Warning:
Attackers can spoof SMS and hijack a person's phone number. Operators can also recycle phone numbers for new users after closing an account. While SMS OTP is useful for verifying a phone number for the above use cases, we recommend using additional and stronger forms of authentication (such as multi-factor and the Web authentication API to establish new sessions for these users.
Actual state
The following table explains the current state of the Web OTP API.
He passed |
Condition |
---|---|
1. Create an explainer |
To complete |
2. Create initial draft specification |
To complete |
3. Collect feedback and repeat the design |
To complete |
4. Proof of origin |
To complete |
5. Launch |
Chromium 84 |
Changes from previous versions
The first versions of this API were called SMS Receiver. If you are familiar with that version of the API, consider the changes made. SMS Receiver API enhancements include:
- The SMS message format is now aligned with WebKit.
- The web page only receives an OTP code regardless of anything else in the message.
- El código hash de la aplicación del browser ya no es necesario en el mensaje.
See it in action
Suppose a user wants to verify his phone number with a website. The website sends a text message to the user by SMS and the user enters the OTP from the message to verify the ownership of the phone number.
With the Web OTP API, these steps are as easy as one touch for the user, as shown in the video. When the text message arrives, a bottom sheet appears and asks the user to verify their phone number. After clicking the check
on the bottom sheet, the browser pastes the OTP into the form and the form is submitted without the user having to press Follow, continue.
The whole process is diagrammed in the following image.

Web OTP API Diagram
Try the demo usted mismo. No solicita su número de teléfono ni envía un SMS a su dispositivo, pero puede enviar uno desde otro dispositivo copiando el texto que se muestra en la demostración. Esto funciona porque no importa quién be el remitente cuando se utiliza la API de Web OTP.
- Go https://web-otp.glitch.me in Chrome 84 or later on an Android device.
- Send the following SMS text message to your phone from the other phone.
@ web-otp.glitch.me #12345
Did you receive the SMS and see the message to enter the code in the entry area? This is how the OTP Web API works for users.
Caution:
- If the sender's phone number is included in the recipient's contact list, this API will not be activated due to the design of the underlying. SMS user consent API.
- If you are using a work profile on your Android device and the Web OTP is not working, try installing and using Chrome on your personal profile (that is, the same profile that you receive SMS messages on).
Using the Web OTP API consists of three parts:
- A correctly annotated
label
- JavaScript en su aplicación web
- Formatted text message sent by SMS.
I will cover the tag first.
Write down a
label
Web OTP en sí mismo funciona sin ninguna anotación HTML, pero para la compatibilidad entre browsers, le recomiendo que agregue autocomplete = "one-time-code"
to the tag where you expect the user to enter an OTP.
This allows Safari 14 or later to suggest that the user automatically complete the
field with an OTP when they receive an SMS with the format described in Format the SMS message even if it is not compatible with Web OTP.
HTML
<form>
<input autocomplete="one-time-code" required/>
<input type="submit">
</form>
Use the Web OTP API
Because Web OTP is simple, just copy and paste the following code. I'll walk you through what's going on anyway.
JavaScript
if ('OTPCredential' in window) {
window.addEventListener('DOMContentLoaded', and => {
const input = document.querySelector('input[autocomplete="one-time-code"]');
if (!input) return;
const ac = new AbortController();
const form = input.closest('form');
if (form) {
form.addEventListener('submit', and => {
ac.abort();
});
}
navigator.credentials.get({
otp: { transport:['sms'] },
signal: ac.signal
}).then(otp => {
input.value = otp.code;
if (form) form.submit();
}).catch(err => {
console.log(err);
});
});
}
Feature detection
Feature detection is the same as for many other APIs. Hear
DOMContentLoaded
The event esperará a que el árbol DOM esté listo para realizar consultas.
JavaScript
if ('OTPCredential' in window) {
window.addEventListener('DOMContentLoaded', and => {
const input = document.querySelector('input[autocomplete="one-time-code"]');
if (!input) return;
…
const form = input.closest('form');
…
});
}
Caution:
La API Web OTP requiere un origen seguro (HTTPS). La detección de funciones en un sitio web HTTP fallará.
Process the OTP
The Web OTP API itself is pretty simple. Use
navigator.credentials.get ()
to get the OTP. Web OTP adds a new otp
option to that method. It only has one property: transport
, whose value must be an array with the string 'sms'
.
JavaScript
…
navigator.credentials.get({
otp: { transport:['sms'] }
…
}).then(otp => {
…
This activates the browser permission flow when an SMS message arrives. If permission is granted, the returned promise is resolved with a OTPCredential
object.
Content de obtenido OTPCredential
object
{
code: "123456"
type: "otp"
}
Then pass the OTP value to field. Submitting the form directly will eliminate the step that requires the user to tap a button.
JavaScript
…
navigator.credentials.get({
otp: { transport:['sms'] }
…
}).then(otp => {
input.value = otp.code;
if (form) form.submit();
}).catch(err => {
console.error(err);
});
…
Abort the message
In case the user manually enters an OTP and submits the form, they can cancel the
get ()
call using a AbortController
instance in the options
object.
JavaScript
…
const ac = new AbortController();
…
if (form) {
form.addEventListener('submit', and => {
ac.abort();
});
}
…
navigator.credentials.get({
otp: { transport:['sms'] },
signal: ac.signal
}).then(otp => {
…
Format the SMS message
The API itself should seem simple enough, but there are a few things to know before using it. The message must be sent after
navigator.credentials.get ()
is called and must be received on the device where get ()
was called. Finally, the message must adhere to the following format:
- El mensaje comienza con texto legible por humanos (opcional) dejando la última línea para la Url y la OTP.
- The host part of the website URL that invoked the API must be preceded by
@
. - The URL must contain a pound sign ('
#
') followed by the OTP.
For example:
Your OTP is: 123456.@www.example.com #123456
Population
Try various messages with the demo:
https://web-otp.glitch.me
You can also fork it and create your version:
https://glitch.com/edit/#!/web-otp.
Frequently asked questions
Where do I report errors in the Chrome deployment?
Found a bug with the Chrome implementation?
- File a bug in
https://new.crbug.com. Include as much detail as you can, simple instructions to reproduce and set up Components toBlink> WebOTP
.
How can I help with this feature?
¿Está pensando en utilizar la API de Web OTP? Su apoyo público nos ayuda a priorizar las funciones y muestra a otros proveedores de navegadores lo importante que es darles soporte. Enviar un tweet to @Cromodev with
#webotp
and let us know where and how you are using it.
What are the differences with the SMS receiver API?
Think of the Web OTP API as an evolved version of the SMS Receiver API. The OTP Web API has some significant differences compared to the SMS Receiver API.
- The expected text format for the SMS message has changed.
- It no longer requires an application hash string to be included in the SMS message.
- The called method is now
navigator.credentials.get ()
rather than
navigator.sms.receive ()
. - the
get ()
receive only the OTP instead of the whole SMS message like
receive ()
did before. - It is now possible to abort the call to
get ()
.
Is this API compatible with different browsers?
Chromium and WebKit agreed the SMS text message format and Apple announced Safari support for it starting with iOS 14 and macOS Big Sur. Although Safari does not support the Web OTP JavaScript API, when annotating input
element with autocomplete = ["one-time-code"]
, the default keyboard automatically suggests that you enter the OTP if the SMS message conforms to the format.
Is it safe to use SMS as a form of authentication?
While SMS OTP is useful for verifying a phone number when it is first provided, phone number verification via SMS should be used carefully to re-authenticate as operators can hijack and recycle phone numbers . Web OTP is a convenient recovery and restoration mechanism, but services must combine it with additional factors, such as a knowledge challenge, or use the
Web authentication API
for strong authentication.