Search code examples
azureazure-active-directorycypress

Logging into Azure Ad with Cypress


How can I retrieve an access token via Azure authentication?


Solution

  • I managed to solve the Azure AD login by creating the following Cypress custom command:

    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()