Puppeteer Quick Tip: How to do Basic Authentication
Sony AK
Posted on December 10, 2019
A friend of mine ask about how to do basic authentication on Puppeteer. Fortunately it's quite easy.
Example of website with HTTP Basic Authentication enabled.
Here is the example of Puppeteer to handle HTTP Basic Authentication.
const puppeteer = require('puppeteer');
(async () => {
// set some options, set headless to false so we can see the browser in action
let launchOptions = { headless: false, args: ['--start-maximized'] };
// launch the browser with above options
const browser = await puppeteer.launch(launchOptions);
const page = await browser.newPage();
// set viewport and user agent (just in case for nice viewing)
await page.setViewport({width: 1366, height: 768});
await page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36');
// set the HTTP Basic Authentication credential
await page.authenticate({'username':'YOUR_BASIC_AUTH_USERNAME', 'password': 'YOUR_BASIC_AUTH_PASSWORD'});
// go to website that protected with HTTP Basic Authentication
await page.goto('https://WEBSITE_THAT_PROTECTED_BY_HTTP_BASIC_AUTH');
// close the browser
// await browser.close();
})();
Above code will run Puppeteer on headful mode and on the last part I comment the await browser.close()
to see the browser in action.
The key is this code. It will set Pupeeteer to handle the basic authentication on a website.
await page.authenticate({'username':'YOUR_BASIC_AUTH_USERNAME', 'password': 'YOUR_BASIC_AUTH_PASSWORD'});
I hope you enjoy it. Thank you.
💖 💪 🙅 🚩
Sony AK
Posted on December 10, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.