Social login using your personal Google or Google Gsuite account is a common use case for many login scenarios.
Steps
- We start at a site that offers Google as an authentication provider. In this case we use Stack Overflow (opens new window).
- We fetch the login page and click the "Login with Google" button.
- We are redirect to Google.
- We provide the username and password, injected by using environment variables.
- We are redirected back to the starting.
const puppeteer = require("puppeteer");
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 800 });
await page.goto("https://stackoverflow.com/users/login");
const navigationPromise = page.waitForNavigation();
await page.waitForSelector("button.s-btn__google");
await page.click("button.s-btn__google");
await navigationPromise;
await page.waitForSelector('input[type="email"]');
await page.type('input[type="email"]', process.env.GOOGLE_USER);
await page.click("#identifierNext");
await page.waitForSelector('input[type="password"]', { visible: true });
await page.type('input[type="password"]', process.env.GOOGLE_PWD);
await page.waitForSelector("#passwordNext", { visible: true });
await page.click("#passwordNext");
await navigationPromise;
await browser.close();
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const { webkit } = require("playwright");
(async () => {
const browser = await webkit.launch();
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 800 });
await page.goto("https://stackoverflow.com/users/login");
await page.click("button.s-btn__google");
await page.fill('input[type="email"]', process.env.GOOGLE_USER);
await page.click("#identifierNext");
await page.fill('input[type="password"]', process.env.GOOGLE_PWD);
await page.click("#passwordNext");
await browser.close();
})();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Run this example as follows. Replace the username and password placeholder with your own credentials.
GOOGLE_USER=username GOOGLE_PWD=password node mslive-login.js
1
SET GOOGLE_USER=username
SET GOOGLE_PWD=password
node google-login.js
1
2
3
TIP
This example does not work when you have 2-factor authentication enabled, and you might trigger a recaptcha check.
Takeaways
- Use environment variables to inject secrets.
- Wait for the navigation as your are redirected to Google.
- Wait for the navigation as you are redirected back to the start site.