Reference

Cypress

OtherEvergreenPublic

How to authenticate via Cypress

Programmatically logging in using the dynamically generated CSRF token hidden on the login page.

Steps

  1. Harness the power of cy.request() and send a GET request to the third party/server website. cy.visit() won't work.
  2. Fetch the hidden CSRF token
  3. Login to the application through the /login endpoint of IdentityServer4 with valid credentials
  4. Next, cy.visit() to your home page and Voila! You should be logged in
Cypress.Commands.add('IdentityServerAPILogin', (email, password) => {
  cy.server();

  // Step 1
  cy.request('GET', thirdPartyServerUrl).then(response => {

    // Step 2. Parses the html response to fetch the CSRF token
    const htmlDocument = document.createElement('html');
    htmlDocument.innerHTML = response.body;
    const loginForm = htmlDocument.getElementsByTagName('form')[0];
    const requestVerificationToken = loginForm.elements.__RequestVerificationToken.value;

    // Step 3. Sends a valid request to thirdPartyServerUrl which sets the session cookies on a successful response
    cy.request({
      method: 'POST',
      url: thirdPartyServerUrl + '/loginEndpoint',
      followRedirect: false,
      form: true,
      body: {
        ReturnUrl: '',
        Email: email,
        Password: password,
        __RequestVerificationToken: requestVerificationToken
      }
    });
  });
});

Article

Trying to login to OIDC flow with Cypress? Don’t break your head no more