Skip to main content

Multi-factor authentication (MFA) flows that use time-based one-time passwords (TOTP) can be automated with seleniumbase-rs. The crate generates codes locally from a base32-encoded shared secret, so you can complete MFA login steps without manual intervention.

Info

What you will learn

  • How to generate a TOTP code.
  • How to use the code in a login flow.
  • Security best practices for handling secrets.
Quick reference

get_totp_code(secret) returns the code. Its aliases are get_mfa_code and get_google_auth_code.

enter_totp_code(css, secret) types the code into a field and presses Enter. Its alias is enter_mfa_code.

RFC 6238 with HMAC-SHA1, a 30 second step and 6 digits.

Generate a TOTP code#

get_totp_code is a plain method, not an async one: it reads the clock and computes the code, with no browser call.

The secret is the base32-encoded shared secret provided by the service when enabling MFA. It is often shown as a QR code or a plain string during enrollment. Spaces and dashes in the secret are ignored, and case does not matter. get_mfa_code and get_google_auth_code are aliases of get_totp_code.

Use in a login flow#

Google Authenticator compatibility#

Codes are compatible with Google Authenticator, Authy, Microsoft Authenticator, and other standard TOTP apps (RFC 6238 with HMAC-SHA1). The time step is 30 seconds and the output length is 6 digits.

Warning

Neither can be changed, so a service that uses another length, step or hash will not accept these codes.

Security notes#

Warning
  • Keep MFA secrets out of source code; load them from environment variables or a secrets manager. If you keep one in a file, sbrs encrypt and sbrs decrypt (AES-256-GCM, passphrase from SB_ENCRYPTION_KEY) can protect it at rest.
  • Treat TOTP secrets with the same care as passwords. Rotate them if exposed.
Note

Codes are generated locally; no network request is required.

Troubleshooting#

Code rejected

Likely cause: System clock skew.

Fix: Synchronize the test machine’s clock with NTP.

invalid base32 character error

Likely cause: The secret is not base32 (letters A-Z and digits 2-7).

Fix: Re-copy the secret from the enrollment screen.

Code expires before use

Likely cause: Generated too early.

Fix: Generate the code immediately before typing it.