Last month, I was working on the problem of handling MFA code prompt with Playwright and finally figured out an approach to tackle the problem. I did not blog about it though. But I did share a small video about how it works on Twitter. I then saw Marcus‘s post today on how to handle AD authentication in Playwright, and thought that I should definitely blog about this now.
The key pieces in the sample are:
- Azure Identity library for getting the user name while you are running it from your local machine, or from variable if running using GitHub Actions
- Filling MFA code using otpauth npm package
If you just want to have a look at the code before reading the post, you can head over to https://github.com/rajyraman/playwright-azure-ad-mfa
Approach:
If you already have Microsoft Authenticator with prompt setup, the first step is to ensure that you will use code and not prompt. Head over to https://mysignins.microsoft.com/security-info and add a new sign in method for Authenticator app. Use the account that you will use in Playwright.
Now click on the link that says that you would like to use a different authenticator app.
Rather than scan the QR code click on the button to get the secret code.
Now copy the secret code to your clipboard. You would need this for generating the MFA code.
The last step is to choose “App based authentication or hardware token – code” as default MFA auth method and click the Confirm button.
Once you do this you can add this code along with the account password on the local env file. Since this is a PoC, and I really only want to demonstrate the MFA + Playwright capability, I am storing this in plaintext locally. You would want to store both the TOTP secret and password securely and retrieve them on demand in a production environment. Below is how my I have setup my .env file.
Playwright can also be run via GitHub Actions and so in this case I have securely stored the password and TOTP secret in the repo.
Since I am not too bothered by the URL and Username being shown in the action output I have stored these as variables.
I refer these inside the workflow itself and surface these as environment variables.
This setup allows me to run the test in GitHub Actions also. The runner logs in with username, password and MFA code and runs the test.
Hope this helps with testing Power Apps or any app that is behind Azure AD.
Sample Repo: https://github.com/rajyraman/playwright-azure-ad-mfa
References:
*This post is locked for comments