Simular de forma automática el login a Azure AD con Playwright

Para un escenario en el que estoy trabajando necesito simular de forma automática el acceso a una web en la que debes autenticarte primero con Azure Active Directory. Para ello he usado la herramienta Playwright de Microsoft, una de las opciones que, a día de hoy, potencialmente pueden reemplazar a Selenium.

¿Qué es Playwright?

Playwright se trata de API con la que puedes automatizar Chromium, Firefox y WebKit y así testear tus aplicaciones desde un punto de vista funcional.

https://playwright.dev/

Tiene SDK para Node.js, Java, Python y .NET. En este artículo usaremos esta última.

Login en Azure Active Directorio con Playwright

Para conseguir mi objetivo me he creado una aplicación de Consola:

dotnet new console -n web-with-az-ad-playwright-dotnet

He añadido la librería de Playwright:

dotnet add package Microsoft.Playwright

Y este es el código de ejemplo que he utilizado:

// // See https://aka.ms/new-console-template for more information
using Microsoft.Playwright;
using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });
//3. Authenticate with Azure AD
Console.WriteLine("Testing authenticated web page with Azure AD");
var page = await browser.NewPageAsync();
await page.GotoAsync("<WEB_URL>");
//Interact with the login form:
//email
await page.FillAsync("input[type='email']", "<VALID_USER_EMAIL>");
await page.ClickAsync("input[type='submit']");
await page.WaitForNavigationAsync();
//password
await page.ClickAsync("[placeholder='Password']");
await page.FillAsync("input[name='passwd']", "<VALID_USER_PASSWORD>");
await page.ClickAsync("input[type='submit']");

//Stay signed? Say no
await page.ClickAsync("text=No");
await page.WaitForNavigationAsync();
// await page.PauseAsync(); //Just for debugging
var title = await page.TitleAsync();
Console.WriteLine($"Title of the page {title}");

Nota: si te ha sorprendido el código fuente, o crees que le faltan cosas 😀 , echa un vistazo a este enlace: https://aka.ms/new-console-template

Si lo ejecutas con Headless a false podrás ver cómo se genera una instancia de Chromium y ejecuta de manera rápida todos estos pasos. Si estás haciendo un caso similar y no sabes alguno de los selectores de tu web, puedes usar page.PauseAsync() que parará el proceso y te permitirá explorar los campos de la web y devolverte el selector.

El código del ejemplo lo tienes en mi GitHub.

¡Saludos!