如何创建函数获取Auth0令牌,用于Cypress测试用户身份认证
嘿,作为QA能自己捣鼓Cypress和Auth0令牌认证,已经超棒啦!我来给你捋个清晰的实现思路,都是适合新手的步骤~
用Cypress通过Auth0获取并复用登录令牌的实现方案
核心思路
我们可以直接调用Auth0的认证API获取令牌,把令牌存在Cypress的环境变量或浏览器本地存储里,后续测试直接复用这个令牌,完全跳过UI登录流程(还能避开UI登录的各种坑)。
具体步骤
1. 准备Auth0的配置信息
首先你得从Auth0后台拿到这几个关键参数,别硬编码在代码里,用Cypress的环境文件管理更安全:
domain:你的Auth0域名(比如xxx.auth0.com)clientId:应用的客户端IDclientSecret:应用的客户端密钥(这个要保密!别随便泄露)audience:你的风险评估应用的API标识符scope:需要的权限(比如openid profile email)
把这些参数存在项目根目录的cypress.env.json文件里:
{ "auth0_domain": "your-auth0-domain.auth0.com", "auth0_clientId": "your-client-id", "auth0_clientSecret": "your-client-secret", "auth0_audience": "https://your-risk-app-api.com", "auth0_scope": "openid profile email" }
2. 编写获取令牌的自定义命令
在cypress/support/commands.js里添加一个自定义命令loginByAuth0Api,用Auth0的密码授权流(专门适合测试环境,因为我们有测试用户的账号密码)来获取令牌:
Cypress.Commands.add('loginByAuth0Api', (username, password) => { cy.request({ method: 'POST', url: `https://${Cypress.env('auth0_domain')}/oauth/token`, body: { grant_type: 'password', username: username, password: password, client_id: Cypress.env('auth0_clientId'), client_secret: Cypress.env('auth0_clientSecret'), audience: Cypress.env('auth0_audience'), scope: Cypress.env('auth0_scope') } }).then((response) => { // 把令牌存在localStorage里,模拟应用登录后的状态 window.localStorage.setItem('access_token', response.body.access_token); window.localStorage.setItem('id_token', response.body.id_token); // 也可以把令牌存在Cypress环境变量里,方便其他测试用例调用 Cypress.env('access_token', response.body.access_token); }); });
3. 在测试前复用令牌
如果你想在所有测试前只获取一次令牌,就在cypress/support/e2e.js(旧版本是index.js)里加全局钩子:
before(() => { // 替换成你的测试账号密码 cy.loginByAuth0Api('test-user@yourcompany.com', 'test-password'); });
如果只是某个测试套件需要,就在对应的测试文件里写:
describe('风险评估应用核心功能测试', () => { before(() => { cy.loginByAuth0Api('test-user@yourcompany.com', 'test-password'); }); it('访问仪表盘页面并验证内容', () => { cy.visit('/dashboard'); // 这里已经是登录状态了,直接测试功能就行 cy.contains('风险评估仪表盘').should('be.visible'); }); });
4. 处理令牌过期(可选优化)
如果令牌有效期比较短,你可以在测试前检查令牌是否过期,过期了再重新获取:
// 写个小工具函数判断令牌是否过期 const isTokenExpired = (token) => { if (!token) return true; const decoded = JSON.parse(atob(token.split('.')[1])); return decoded.exp * 1000 < Date.now(); }; before(() => { const existingToken = window.localStorage.getItem('access_token'); if (isTokenExpired(existingToken)) { cy.loginByAuth0Api('test-user@yourcompany.com', 'test-password'); } });
重要注意事项
- 密码授权流只适合测试环境,生产环境绝对不能用!
clientSecret一定要保密,别提交到代码仓库,用环境变量管理是最佳实践- 如果你的应用用的是Auth0的Lock登录组件,也可以用
cy.intercept拦截登录请求直接返回令牌,但API方式更稳定可靠
这样应该就能帮你跳过烦人的UI登录,直接用令牌认证测试啦,有不懂的地方随时琢磨~
内容的提问来源于stack exchange,提问作者Adam A
相关产品推荐
相关产品推荐

