How to use Cypress.io to login using MS Active Directory?

Viewed 2229

I have an Azure hosted App Service website that is protected by Azure Active Directory login. I want to test this site's functionality using Cypress. I had hoped to simply have some known credentials that I use to login to the site. However when I try to cy.visit("https://testmysite.azurewebsites.net/") Cypress gets stuck in an infinite loop as shown in the screenshot below. Any suggestions how I can authenticate to the site and then use Cypress for my automated testing?

enter image description here

2 Answers

Before you perform the first page visit with Cypress, you must first technically log in with a test user at the Active Directory. This can be achieved as follows:

In Cypress you can add your own custom commands like described here: https://docs.cypress.io/api/cypress-api/custom-commands

This way you can write a custom command that technically logs a test user into active directory, e.g.:

Cypress.Commands.add('login', () => {
  return cy
    .request({
      method: 'POST',
      url: `https://login.microsoftonline.com/${tenantId}/oauth2/token`,
      form: true,
      body: {
        grant_type: 'password',
        tenant: 'tenantId',
        client_id: 'clientId',
        client_secret: 'clientSecret',
        username: 'username',
        password: 'password',
        resource: 'clientId',
      },
    })
    .then((response) => {
      sessionStorage.setItem('access_token', response.body.access_token);
    });
});

Then you can use your custom command in your test as first action like:

cy.login();

and then perform your site visit:

cy.visit()
Related