使用 Cypress 在全栈应用程序中使用 Auth0 测试身份验证

Testing authentication with Auth0 in a full stack application with Cypress

我正在开发一个全栈 NestJS 应用程序,使用 express-openid-connect library 与 Auth0 集成。我正在使用 Cypress 进行 e2e 测试,我正在尝试找到一种使用 Cypress 测试我的登录的方法。

我找到了这篇文章 - https://auth0.com/blog/end-to-end-testing-with-cypress-and-auth0/,但它似乎与 React 应用程序密切相关。我正在调用 /oauth/token API 端点,我得到了响应,但我不确定如何构建我的回调 URL 来让我登录到应用程序。这是我目前所拥有的:

Cypress.Commands.add('login', () => {
  cy.session('logged in user', () => {
    const options = {
      method: 'POST',
      url: `${Cypress.env('OAUTH_DOMAIN')}/oauth/token`,
      body: {
        grant_type: 'password',
        username: Cypress.env('AUTH_USERNAME'),
        password: Cypress.env('AUTH_PASSWORD'),
        scope: 'openid profile email',
        audience: `${Cypress.env('OAUTH_DOMAIN')}/api/v2/`,
        client_id: Cypress.env('OAUTH_CLIENT_ID'),
        client_secret: Cypress.env('OAUTH_CLIENT_SECRET'),
      },
    };
    cy.request(options).then((response) => {
      // What do I do here?
    });
  });
});

如有指点,将不胜感激!

我最终通过使用 Puppeteer 处理我的登录来解决这个问题,在重定向到回调 URL 时停止并将 cookie 和回调 URL 返回给赛普拉斯,详见本文:

https://sandrino.dev/blog/writing-cypress-e2e-tests-with-auth0

从那时起,情况发生了一些变化,随着 Cypress experimentalSessionSupport 的引入,它变得更简单了。我最终将解决方案缩减为在我的 Cypress 设置中包含以下内容:

// cypress/plugins/auth0.js

const puppeteer = require('puppeteer');

const preventApplicationRedirect = function (callbackUrl) {
  return (request) => {
    const url = request.url();
    if (request.isNavigationRequest() && url.indexOf(callbackUrl) === 0)
      request.respond({ body: url, status: 200 });
    else request.continue();
  };
};

const writeUsername = async function writeUsername({ page, options } = {}) {
  await page.waitForSelector('#username');
  await page.type('#username', options.username);
};

const writePassword = async function writeUsername({ page, options } = {}) {
  await page.waitForSelector('#password', { visible: true });
  await page.type('#password', options.password);
};

const clickLogin = async function ({ page } = {}) {
  await page.waitForSelector('button[type="submit"]', {
    visible: true,
    timeout: 5000,
  });

  const [response] = await Promise.all([
    page.waitForNavigation({ waitUntil: 'networkidle2' }),
    page.click('button[type="submit"]'),
  ]);
  return response;
};

exports.Login = async function (options = {}) {
  const browser = await puppeteer.launch({
    headless: options.headless,
    args: options.args || ['--no-sandbox', '--disable-setuid-sandbox'],
  });

  const page = await browser.newPage();

  try {
    await page.setViewport({ width: 1280, height: 800 });
    await page.setRequestInterception(true);

    page.on('request', preventApplicationRedirect(options.callbackUrl));

    await page.goto(options.loginUrl);

    await writeUsername({ page, options });
    await writePassword({ page, options });

    const response = await clickLogin({ page, options });

    if (response.status() >= 400) {
      throw new Error(
        `'Login with user ${
          options.username
        } failed, error ${response.status()}`,
      );
    }

    const url = response.url();
    if (url.indexOf(options.callbackUrl) !== 0) {
      throw new Error(`User was redirected to unexpected location: ${url}`);
    }

    const { cookies } = await page._client.send('Network.getAllCookies', {});
    return {
      callbackUrl: url,
      cookies,
    };
  } finally {
    await page.close();
    await browser.close();
  }
};

// cypress/plugins/index.js

const auth0 = require('./auth0');

module.exports = (on, config) => {
  require('dotenv').config({ path: '.env.test' });

  config.env.AUTH0_DOMAIN = process.env.AUTH0_DOMAIN;
  config.env.AUTH_USERNAME = process.env.AUTH_USERNAME;
  config.env.AUTH_PASSWORD = process.env.AUTH_PASSWORD;

  on('task', {
    LoginPuppeteer(options) {
      return auth0.Login(options);
    },
  });

  return config;
};
// cypress/support/commands.js

const { getUnixTime } = require('date-fns');

/*
 * Create the cookie expiration.
 */
function getFutureTime(minutesInFuture) {
  const time = new Date(new Date().getTime() + minutesInFuture * 60000);
  return getUnixTime(time);
}

/**
 * Create a cookie object.
 * @param {*} cookie
 */
function createCookie(cookie) {
  return {
    name: cookie.name,
    value: cookie.value,
    options: {
      domain: `${cookie.domain.trimLeft('.')}`,
      expiry: getFutureTime(15),
      httpOnly: cookie.httpOnly,
      path: cookie.path,
      sameSite: cookie.sameSite,
      secure: cookie.secure,
      session: cookie.session,
    },
  };
}

/**
 * Login via puppeteer and return the redirect url and cookies.
 */
function login() {
  return cy.task('LoginPuppeteer', {
    username: Cypress.env('AUTH_USERNAME'),
    password: Cypress.env('AUTH_PASSWORD'),
    loginUrl: 'http://localhost:3000/login',
    callbackUrl: 'http://localhost:3000/callback',
  });
}

/**
 * Login with Auth0.
 */
Cypress.Commands.add('loginAuth0', () => {
  cy.session('logged in user', () => {
    login().then(({ cookies, callbackUrl }) => {
      console.log(cookies);
      cookies
        .map(createCookie)
        .forEach((c) => cy.setCookie(c.name, c.value, c.options));

      cy.visit(callbackUrl);
    });
  });
});

然后您可以在您的应用中使用 cy.loginAuth0() 来使用真实的 Auth0 实例登录。确保 cypress.json 中有 "experimentalSessionSupport": true。这样你就只需要在你的测试套件中执行一次这个(公认的冗长)任务!