loading...
Cover image for Puppeteer Quick Tip: How to do Basic Authentication

Puppeteer Quick Tip: How to do Basic Authentication

sonyarianto profile image Sony AK ・1 min read

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.

Alt Text

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.

Posted on by:

Discussion

markdown guide
 

This works awesome in windows machine. Do we need to tweak anything to support in Linux. When i m executing this same code in docker container, seeing timeout error. Can you please suggest if you have any solution?

 

Hi Deva, I am using Linux (Ubuntu) and so far it has no problem, I think all browser implement for basic auth. For the timeout error it might caused by something else, maybe you should debug it first.