table of contents Table of contents

How to Automate Microsoft Live Login with Playwright

On this page

Playwright allows us to automate logging in to a Microsoft Online account.

Steps

  1. We start at https://login.microsoftonline.com/
  2. We provide the username and password, injected by using environment variables
  3. We are redirected to the main account page
ms-account-login.spec.ts
import { test } from '@playwright/test'

test('test', async ({ page }) => {
  await page.goto('https://login.microsoftonline.com/')

  await page.getByRole('heading', { name: 'Sign in' }).click()
  await page.getByPlaceholder('Email address, phone number').fill(process.env.MS_USERNAME)
  await page.getByRole('button', { name: 'Next' }).click()

  await page.getByTestId('i0118').fill(process.env.MS_PASSWORD)
  await page.getByTestId('textButtonContainer').getByRole('button', { name: 'Sign in' }).click()
  await page.getByTestId('checkboxField').check()
  await page.getByLabel('Stay signed in?').click()
})

Run this example as follows. Replace the username and password placeholder with your own credentials.

Terminal
MS_USER=username MS_PWD=password npx playwright test ms-account-login.spec.ts
Terminal
SET MS_USER=username
SET MS_PWD=password
npx playwright test ms-account-login.spec.ts

This example does not work when you have 2-factor authentication enabled, and you might trigger a recaptcha check.

Takeaways

  1. Use environment variables to inject secrets.
  2. Wait for the navigation as your are redirected to Microsoft.
  3. Wait for the navigation as you are redirected back to the start site.

Last updated on December 11, 2024. You can contribute to this documentation by editing this page on Github