Fill OTP forms within cross-origin iframes with WebOTP API

Table of contents

No heading

No headings in the article.

Implementing One-Time Passwords (OTP) with an iframe

One-time passwords (OTP) are a commonly used method for securing online accounts and transactions. OTPs are typically delivered via SMS or email, and are only valid for a single use. In this article, we'll explore how to implement OTPs in a web application using an iframe.

To begin, you'll need to generate an OTP and deliver it to the user. This can be done through a third-party service, such as Twilio or SendGrid, or you can build your own solution using a library like OTP.js. Once the OTP has been delivered, the user can enter it into your web application to complete the login or transaction process.

const otp = await navigator.credentials.get({
    otp: { transport:['sms'] }
  });
…
Your OTP is: 123456.

@web-otp.glitch.me #12345

To securely handle the OTP within your web application, you can use an iframe to create a separate, isolated environment for the OTP input form. This helps protect against attacks such as cross-site scripting (XSS) or phishing, as the iframe cannot be accessed or manipulated by external sources.

To create the iframe, you can use the iframe element in your HTML code. You can specify the source of the iframe with the src attribute, and set the width and height of the iframe with the width and height attributes. You can also use the sandbox attribute to further restrict the capabilities of the iframe and protect against potential security vulnerabilities.

Once the iframe is in place, you can use JavaScript to communicate with it and pass data between the iframe and the parent page. To do this, you can use the postMessage function to send messages between the iframe and the parent page, and the onmessage event to receive and process messages on the other side.

In summary, implementing OTPs in a web application using an iframe can help protect against security threats and ensure the integrity of sensitive transactions. By generating and delivering OTPs through a third-party service or custom solution, and using an iframe and postMessage to securely handle the OTP within your web application, you can provide a secure and convenient user experience.

Did you find this article valuable?

Support Raphael Carlos Rego by becoming a sponsor. Any amount is appreciated!