Skip to content

Instantly share code, notes, and snippets.

@pieterdv
Created May 30, 2018 12:01
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save pieterdv/82773fbe036719479d76ab0a4985dc3b to your computer and use it in GitHub Desktop.
Save pieterdv/82773fbe036719479d76ab0a4985dc3b to your computer and use it in GitHub Desktop.
Login through Azure AD with puppeteer
function getAadToken(user, password, identifier) {
return puppeteer.launch({ headless: true }).then(async browser => {
try {
const page = await browser.newPage();
await page.goto("SITEURL");
await page.click(
"LOGINBUTTON"
);
await page.waitFor(2000);
await page.click("input[name=passwd]");
await page.type("input[name=loginfmt]", user, {
delay: 50
});
await page.waitFor(500);
await page.click("input[type=submit]");
await page.waitFor(500);
await page.click("input[name=passwd]");
await page.waitFor(500);
await page.type("input[name=passwd]", password, {
delay: 50
});
await page.waitFor(500);
await page.click("input[type=submit]");
await page.waitForSelector("SELECTOR-ON-WEBSITE-TO-MAKE-SURE-YOU-ARE-BACK-ON-WEBSITE", { visible: true });
let aadValues = await page.evaluate(() => {
let values = {};
for (var i = 0, len = localStorage.length; i < len; ++i) {
if (
localStorage.key(i).startsWith("msal.") ||
localStorage.key(i).startsWith('{"authority":')
) {
values[localStorage.key(i)] = localStorage.getItem(
localStorage.key(i)
);
}
}
return values;
});
browser.close();
fs.readFile("aad-tokens.ts", "utf8", (err, data) => {
let regex = new RegExp(
`export const\\s*${identifier}\\s*=\\s*{(.|\\n)*?};`
);
let result = data.replace(
regex,
`export const ${identifier} = ${JSON.stringify(aadValues)};`
);
fs.writeFile("aad-tokens.ts", result, "utf8");
});
console.log(`${identifier} completed`);
} catch (error) {
console.log(error);
browser.close();
}
});
@sherlinecalista
Copy link

Hi! I am facing some issues while automating login in Microsoft using puppeteer. Can you help me out?

@dahoum
Copy link

dahoum commented Dec 2, 2021

What are the issues you are facing?

@kovacsdongo
Copy link

I have a loop with cypress after azure az login
Is tehere any solution for it?

@Navinox
Copy link

Navinox commented Apr 29, 2022

I have the same problem with cypress. I am looking for a workarround getting the toke but in my project use that on a internal variable and it is imposible to get it. I dont know if puppeteer had the same problem with azure b2c login.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment