Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer - Authorize device (2FA)

Is there a way to authorize Puppeteer for 2FA authentication?

Scenario:

  1. Run Puppeteer and visit a 2FA protected URL
  2. Enter credentials and wait for redirection
  3. Request one-time passcode
  4. Enter the passcode
  5. Wait for redirection
  6. Close the Puppeteer instance

  7. Run Puppeteer and visit a 2FA protected URL

  8. The protected page should be loaded not asking for the passcode anymore

This scenario doesn't work in my case :(

Any other library that can go successfully through this scenario?

like image 441
stedejan Avatar asked Oct 16 '25 03:10

stedejan


1 Answers

There are two possible scenarios to handle 2FA using puppeteer, depending on the nature of the situation (it's not entirely clear from the way you phrase the question).

  1. Replicating session data (in this scenario, you can't have someone provide you the code the second time, you need to bypass it in the future altogether):

I'm going to assume the site you are dealing with is performing some sort of analysis on the browser to determine whether to prompt for a 2FA code or not. In my experience, sometimes there is a random element to this that you can't control, but replicating the exact browser state (user data, cookies, everything) is a start. Pair that with a consistent IP address that has answered correctly previously, and I think chances are very very good.

See my code here, or if that is too heavy, here is a simple implementation of the functions I'm using to save the session data: simple code. In short, I'm converting the session data, cookies- everything that distinguishes that instance of chromium and stuffing it into a base64 string, then later I simply load that data and assume the exact state the browser had previously. I'm pretty sure this is what you want.

  1. Interactive Bot

I'm unsure if this applies to your use-case, but I faced a situation where I needed to pull 2FA codes from a user's phone/email in real-time while the puppeteer was in the middle of performing a login process. The browser could not re-launch because the 2FA code would no longer be valid. It's not a trivial problem. I ended up using Redis and built a framework puppeteer-theater that addressed this use-case among pretty much every scraping/automation workflow I have encountered.

Feel free to reach out if you are looking for specific help.

like image 188
Nico Mee Avatar answered Oct 19 '25 09:10

Nico Mee