@121watts/cypress-nextjs-auth0 中文文档教程

发布于 4年前 浏览 32 更新于 3年前

cypress-nextjs-auth0

构建状态 npm

Contents

Installation

Step 1: Install the addon

yarn add cypress-nextjs-auth0 --dev

Step 2: Import the commands

// cypress/support/index.js

import 'cypress-nextjs-auth0';

Step 2: Register the task

// cypress/plugins/index.js

const encryptTask = require('cypress-nextjs-auth0/encrypt');

module.exports = (on, config) => {
  on('task', encryptTask)
}

Step 3: Create a test user

在您将专门用于测试的 Auth0 应用程序中创建一个用户。

安全考虑中你会看到Auth0 推荐您为每个环境使用单独的租户(例如开发测试生产等)。 考虑在特定于测试的 Auth0 租户中创建此测试用户。

您需要此用户的电子邮件和密码才能完成第 4 步中的 auth0Usernameauth0Password

Step 4: Add Auth0 credentials

使用 Cypress 支持的方法之一(此代码示例假设您使用的是 cypress.env.json 文件)。

用您的 Auth0 应用程序的值替换值:

// cypress.env.json

{
  "auth0Audience": "https://lyft.auth0.com/api/v2/",
  "auth0Domain": "lyft.auth0.com",
  "auth0ClientId": "FNfof292fnNFwveldfg9222rf",
  "auth0ClientSecret": "FNo3i9f2fbFOdFH8f2fhsooi496bw4uGDif3oDd9fmsS18dDn",
  "auth0CookieSecret": "DB208FHFQJFNNA28F0N1F8SBNF8B20FBA0BXSD29SSJAGSL12D9922929D",
  "auth0Password": "mysupersecurepassword",
  "auth0Scope": "openid profile email",
  "auth0SessionCookieName": "appSession",
  "auth0Username": "testuser@lyft.com"
}

auth0Usernameauth0Password 之外的所有内容都应与您应用程序的现有 Auth0 设置相匹配。

auth0Usernameauth0Password 是您在第 3 步中创建的测试用户的电子邮件和密码。

Step 5: Configure Auth0

第 5.1 步:转到您的 Auth0 应用程序设置并启用密码授权类型:

auth0- grant-types

第 5.2 步:转到您的Auth0 租户设置(确保租户名称在页面左上角是正确的)并将默认目录设置为 Username-Password-Authentication:

auth0-default-directory

如果您更改了默认目录的名称(即租户的默认数据库名称),您应该替换 Username-Password -Authentication 使用您的数据库名称,如 Auth0 UI 中所示。 单击 Auth0 仪表板侧栏中的“数据库”以查看您的数据库。

第 5.3 步:将您的 cypress 端口 URL(例如 http://localhost:3001)添加到您的 Auth0 应用程序的“允许来源 (CORS)”列表中:

如果您不这样做但是在运行 Cypress 时指定一个端口,您需要将一个端口添加到您的 cypress.json 文件中。 例如:

// cypress.json

{
  "port": 3001
}

有时用户报告也需要在 Cypress 中添加禁用 chromeWebSecurity

// cypress.json

{
  "port": 3001,
  "chromeWebSecurity": false
}

Usage

以下命令现在可以在您的测试套件中使用: 在测试

login()

Property Type Default value Required?
credentials Object None No
    credentials.username String Cypress.env('auth0Username') No
    credentials.password String Cypress.env('auth0Password') No

开始时调用登录。 例如:

context('Logging in', () => {
  it('should login', () => {
    cy.login().then(() => {

      // Now run your test...
      cy.request('/api/me').then(({ body: user }) => {
        expect(user.email).to.equal(Cypress.env('auth0Username'));
      });
    });
  });
});

或者在 beforeEach() 循环中。 例如:

context('Logging in', () => {

  beforeEach(() => {
    cy.login();
  })

  it('should login', () => {
    cy.request('/api/me').then(({ body: user }) => {
      expect(user.email).to.equal(Cypress.env('auth0Username'));
    });
  });
});

您还可以将 credentials 传递给 login()

context('Logging in', () => {
  it('should login', () => {
    cy.login({
      username: 'anothertestuser@lyft.com',
      password: 'mygreatpassword',
    }).then(() => {

      // Now run your test...
      cy.request('/api/me').then(({ body: user }) => {
        expect(user.email).to.equal(Cypress.env('auth0Username'));
      });
    });
  });
});

如果您想要多个测试用户,建议将他们的凭据包含在 cypress.env.json< /code> 而不是在您的源代码中。

logout()

cy.logout();
Property Type Default value Required?
returnTo String None No

在测试中的任何地方调用 logout()。 例如:

context('Logging out', () => {

  it('should logout', () => {
    cy.login().then(() => {
      cy.visit('/');

      cy.request('/api/me').then(({ body: user }) => {
        expect(user.email).to.equal(Cypress.env('auth0Username'));
      });

      cy.logout();

      cy.request('/api/me', {
        failOnStatusCode: false,
      }).then((response) => {
        expect(response.status).to.equal(401); // Assert user is logged out
      });
    });
  });

});

您可以将返回 URL 传递给 logout(),用户将在成功注销后转到该网址:

context('Logging out', () => {

  it('should logout', () => {
    cy.login().then(() => {
      cy.visit('/');

      cy.logout('/thanks-for-visiting');
    });
  });
});

您可能希望在每次测试后注销:

// cypress/support.index.js

import 'cypress-nextjs-auth0';

beforeEach(() => {
  cy.logout();
})

Security considerations

Use separate tenants

Auth0 建议您为每个环境使用单独的租户(例如开发测试、<代码>生产等)。 这将有助于降低创建测试用户的风险。

因此,如果您的 testing 环境没有专门的租户,建议您创建一个新租户并更新其设置以匹配您的 development 环境,然后再执行 安装步骤

Storing credentials

将测试凭据放入 cypress.env.json 或您可以远离源代码控制的类似位置。

如果您使用 cypress.env.json,请将文件添加到您的 .gitignore.npmignore 文件中,如下所示:

# .gitignore

cypress.env.json

Continuous integration

如果您使用平台所有 CI 的一部分,例如 Travis,您需要将所有敏感数据保留在测试日志之外。

有关有关如何防止“泄漏”Travis 日志的更多信息,请参阅此处

Contributing

为了贡献这个插件,克隆 repo:

git clone https://github.com/sir-dunxalot/cypress-nextjs-auth0.git

安装依赖项:

yarn install

运行虚拟应用服务器:

yarn dev

最后,运行测试套件(当虚拟应用服务器正在运行时):

yarn test:ui # or yarn test:headless for no UI

要在本地运行测试套件,您需要将一些环境变量传递给Next.js 和 Cypress...

最简单的方法是添加以下两个文件(它们被排除在源代码控制之外),但您也可以通过另一种方式传递它们包含的环境变量(例如 export CYPRESS_auth0ClientId=FNfof292fnNFwveldfg9222rf ):

  • cypress.env.json
  • cypress/dummy/.env

要获取这些环境变量的值,您可以:

  • Open an PR and then ask @sir-dunxalot to share test credentials
  • Use values from your own Auth0 test tenant and app (since these files are not check in to source control)
  • Create a new (free tier) tenant and application in Auth0 and set it up as documented in the installation steps

如果您使用自己的 Auth0 租户,请注意您需要两个测试用户(auth0Usernameauth0UsernameAlt ).

这是 Cypress 环境变量(例如在 cypress.env.json 中):

// cypress.env.json

{
  "auth0Audience": "https://lyft.auth0.com/api/v2/",
  "auth0Domain": "lyft.auth0.com",
  "auth0ClientId": "FNfof292fnNFwveldfg9222rf",
  "auth0ClientSecret": "FNo3i9f2fbFOdFH8f2fhsooi496bw4uGDif3oDd9fmsS18dDn",
  "auth0CookieSecret": "DB208FHFQJFNNA28F0N1F8SBNF8B20FBA0BXSD29SSJAGSL12D9922929D",
  "auth0Password": "mysupersecurepassword",
  "auth0PasswordAlt": "anothersupersecurepassword",
  "auth0Scope": "openid profile email",
  "auth0SessionCookieName": "appSession",
  "auth0Username": "testuser@lyft.com",
  "auth0UsernameAlt": "testuser@lyft.com"
}

这是 Next.js 应用程序变量(例如在 cypress/dummy/.env 中)。

# cypress/dummy/.env

AUTH0_CLIENT_SECRET='FNo3i9f2fbFOdFH8f2fhsooi496bw4uGDif3oDd9fmsS18dDn'
AUTH0_SECRET='DB208FHFQJFNNA28F0N1F8SBNF8B20FBA0BXSD29SSJAGSL12D9922929D'

AUTH0_CLIENT_ID='FNfof292fnNFwveldfg9222rf'
AUTH0_AUDIENCE='https://lyft.auth0.com/api/v2/'
AUTH0_SCOPE='openid profile email'
AUTH0_ISSUER_BASE_URL='https://lyft.auth0.com'
AUTH0_BASE_URL='http://localhost:3000'

当您打开 PR 或推送到此 repo 的分支时,Travis 将运行测试。 您无需担心添加环境变量,因为它们已作为 Travis 环境变量 添加已经。

Releasing

项目合作者将构建项目并使用 yarn release 命令发布它,该命令将任何参数传递给 发布包

例如:

yarn release patch # e.g. 1.0.0 --> 1.0.1
yarn release minor # e.g. 1.0.0 --> 1.1.0
yarn release major # e.g. 1.0.0 --> 2.0.0
yarn release 1.2.4 # e.g. 1.0.0 --> 1.2.4

cypress-nextjs-auth0

Build Status npm

Contents

Installation

Step 1: Install the addon

yarn add cypress-nextjs-auth0 --dev

Step 2: Import the commands

// cypress/support/index.js

import 'cypress-nextjs-auth0';

Step 2: Register the task

// cypress/plugins/index.js

const encryptTask = require('cypress-nextjs-auth0/encrypt');

module.exports = (on, config) => {
  on('task', encryptTask)
}

Step 3: Create a test user

Create a user in your Auth0 app that you will use specifically for testing.

In security considerations you will see that Auth0 recommends you use separate tenant for each environment (e.g. development, testing, production, etc). Consider creating this test user in a test-specific Auth0 tenant.

You'll need this user's email and password to complete auth0Username and auth0Password in step 4.

Step 4: Add Auth0 credentials

Add the following environment variables using one of Cypress' supported methods (this code example assumes you are using a cypress.env.json file).

Replacing values with your Auth0 application's values:

// cypress.env.json

{
  "auth0Audience": "https://lyft.auth0.com/api/v2/",
  "auth0Domain": "lyft.auth0.com",
  "auth0ClientId": "FNfof292fnNFwveldfg9222rf",
  "auth0ClientSecret": "FNo3i9f2fbFOdFH8f2fhsooi496bw4uGDif3oDd9fmsS18dDn",
  "auth0CookieSecret": "DB208FHFQJFNNA28F0N1F8SBNF8B20FBA0BXSD29SSJAGSL12D9922929D",
  "auth0Password": "mysupersecurepassword",
  "auth0Scope": "openid profile email",
  "auth0SessionCookieName": "appSession",
  "auth0Username": "testuser@lyft.com"
}

Everything except auth0Username and auth0Password should match your app's existing Auth0 settings.

auth0Username and auth0Password are the email and password of the test user you created in step 3.

Step 5: Configure Auth0

Step 5.1: Go to your Auth0 Application settings and enable the Password Grant Type:

auth0-grant-types

Step 5.2: Go to your Auth0 tenant's settings (make sure tenant name is correct in top-left of the page) and set the default directory to Username-Password-Authentication:

auth0-default-directory

If you have changed the name of your default directory (i.e. your tenant's default database name), you should replace Username-Password-Authentication with your database's name, as it's shown in the Auth0 UI. Click on 'databases' in the sidebar of the Auth0 dashboard to view your database(s).

Step 5.3: Add your cypress port URL (e.g. http://localhost:3001) to your Auth0 Application's 'Allowed Origins (CORS)' list:

If you don't yet specify a port when you run Cypress you will need to add a port to your cypress.json file. For example:

// cypress.json

{
  "port": 3001
}

Sometimes user report needing to add disable chromeWebSecurity in Cypress too:

// cypress.json

{
  "port": 3001,
  "chromeWebSecurity": false
}

Usage

The following commands are now available in your test suite:

login()

Property Type Default value Required?
credentials Object None No
    credentials.username String Cypress.env('auth0Username') No
    credentials.password String Cypress.env('auth0Password') No

Call login at the start of a test. For example:

context('Logging in', () => {
  it('should login', () => {
    cy.login().then(() => {

      // Now run your test...
      cy.request('/api/me').then(({ body: user }) => {
        expect(user.email).to.equal(Cypress.env('auth0Username'));
      });
    });
  });
});

Or in a beforeEach() loop. For example:

context('Logging in', () => {

  beforeEach(() => {
    cy.login();
  })

  it('should login', () => {
    cy.request('/api/me').then(({ body: user }) => {
      expect(user.email).to.equal(Cypress.env('auth0Username'));
    });
  });
});

You can also pass credentials to login():

context('Logging in', () => {
  it('should login', () => {
    cy.login({
      username: 'anothertestuser@lyft.com',
      password: 'mygreatpassword',
    }).then(() => {

      // Now run your test...
      cy.request('/api/me').then(({ body: user }) => {
        expect(user.email).to.equal(Cypress.env('auth0Username'));
      });
    });
  });
});

If you want multiple test users, it's recommended to include their credentials in cypress.env.json rather than in your source code.

logout()

cy.logout();
Property Type Default value Required?
returnTo String None No

Call logout() anywhere in a test. For example:

context('Logging out', () => {

  it('should logout', () => {
    cy.login().then(() => {
      cy.visit('/');

      cy.request('/api/me').then(({ body: user }) => {
        expect(user.email).to.equal(Cypress.env('auth0Username'));
      });

      cy.logout();

      cy.request('/api/me', {
        failOnStatusCode: false,
      }).then((response) => {
        expect(response.status).to.equal(401); // Assert user is logged out
      });
    });
  });

});

You can pass a return URL to logout(), which the user will be taken to after a successful logout:

context('Logging out', () => {

  it('should logout', () => {
    cy.login().then(() => {
      cy.visit('/');

      cy.logout('/thanks-for-visiting');
    });
  });
});

You may want to logout after every test:

// cypress/support.index.js

import 'cypress-nextjs-auth0';

beforeEach(() => {
  cy.logout();
})

Security considerations

Use separate tenants

Auth0 recommends you use a separate tenant for each environment (e.g. development, testing, production, etc). This will help mitigate the risk of creating test users.

Therefore, if you don't have a dedicated tenant for your testing environment, it's recommended you create a new tenant and update its setting to match your development environment before following the installation steps.

Storing credentials

Put test credentials in cypress.env.json or a similar place that you can keep out of source control.

If you use cypress.env.json, add the file to your .gitignore and .npmignore files as follows:

# .gitignore

cypress.env.json

Continuous integration

If you use a platform for some of all of CI, like Travis, you will need to keep any sensitive data outside your test logs.

For more info on how to prevent 'leaky' Travis logs, see here.

Contributing

To contribute to this addon, clone the repo:

git clone https://github.com/sir-dunxalot/cypress-nextjs-auth0.git

Install dependencies:

yarn install

Run the dummy app server:

yarn dev

Finally, run the test suite (while the dummy app server is running):

yarn test:ui # or yarn test:headless for no UI

To run the test suites locally you will need to pass some environment variables to Next.js and Cypress…

The easiest way to do this is to add the following two files (they're excluded from source control), but you can also pass their contained environment variables in another way (e.g. export CYPRESS_auth0ClientId=FNfof292fnNFwveldfg9222rf):

  • cypress.env.json
  • cypress/dummy/.env

To get values for these environment variables you can:

  • Open an PR and then ask @sir-dunxalot to share test credentials
  • Use values from your own Auth0 test tenant and app (since these files are not check in to source control)
  • Create a new (free tier) tenant and application in Auth0 and set it up as documented in the installation steps

If you use your own Auth0 tenant, notice that you need two test users (for auth0Username and auth0UsernameAlt).

Here are the Cypress environment variables (e.g. in cypress.env.json):

// cypress.env.json

{
  "auth0Audience": "https://lyft.auth0.com/api/v2/",
  "auth0Domain": "lyft.auth0.com",
  "auth0ClientId": "FNfof292fnNFwveldfg9222rf",
  "auth0ClientSecret": "FNo3i9f2fbFOdFH8f2fhsooi496bw4uGDif3oDd9fmsS18dDn",
  "auth0CookieSecret": "DB208FHFQJFNNA28F0N1F8SBNF8B20FBA0BXSD29SSJAGSL12D9922929D",
  "auth0Password": "mysupersecurepassword",
  "auth0PasswordAlt": "anothersupersecurepassword",
  "auth0Scope": "openid profile email",
  "auth0SessionCookieName": "appSession",
  "auth0Username": "testuser@lyft.com",
  "auth0UsernameAlt": "testuser@lyft.com"
}

Here are the Next.js app variables (e.g. in cypress/dummy/.env).

# cypress/dummy/.env

AUTH0_CLIENT_SECRET='FNo3i9f2fbFOdFH8f2fhsooi496bw4uGDif3oDd9fmsS18dDn'
AUTH0_SECRET='DB208FHFQJFNNA28F0N1F8SBNF8B20FBA0BXSD29SSJAGSL12D9922929D'

AUTH0_CLIENT_ID='FNfof292fnNFwveldfg9222rf'
AUTH0_AUDIENCE='https://lyft.auth0.com/api/v2/'
AUTH0_SCOPE='openid profile email'
AUTH0_ISSUER_BASE_URL='https://lyft.auth0.com'
AUTH0_BASE_URL='http://localhost:3000'

When you open a PR or push to a branch of this repo, Travis will run tests. You don't need to worry about adding environment variables since they've been added as Travis environment variables already.

Releasing

Project collaborators will build the project and release it using the yarn release command, which passes any params to the release-it package.

For example:

yarn release patch # e.g. 1.0.0 --> 1.0.1
yarn release minor # e.g. 1.0.0 --> 1.1.0
yarn release major # e.g. 1.0.0 --> 2.0.0
yarn release 1.2.4 # e.g. 1.0.0 --> 1.2.4
更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文