我正在尝试为 Cypress 创建登录命令,并注意到他们关于如何执行此操作的博客与 Auth0 React SDK 的预期值不匹配。看来他们使用了自定义 express 应用来处理登录,而使用 SDK 来处理此问题(根据 offical Auth0 documentation)。
Cypress official documentation 生成一个本地存储键值对,如下所示。
const item = {
body: {
decodedToken: {
claims,
user: { ... },
audience,
client_id,
},
},
expiresAt: exp,
}
window.localStorage.setItem('auth0Cypress', JSON.stringify(item))
然而,由 Auth0 React SDK 创建的结果类似于:
const item = {
body: {
access_token,
audience,
client_id,
decodedToken: {
claims,
user: { ... },
encoded,
header
},
expires_in,
id_token,
scope,
token_type
},
expiresAt: exp
}
window.localStorage.setItem(`@@auth0spajs@@::${client_id}::${audience}::${scope}`, JSON.stringify(item))
我能够使 https://${auth)_domain}/oauth/token
请求正常工作,但是我无法弄清楚如何从响应中获取数据以使其适合 Auth0 react SDK 想要的数据结构。
有人成功了吗?
在进行一些探索后,我从 /oauth/token
返回的响应似乎不包含 Auth0 React SDK 在登录时输出的值的所有字段。
我还注意到关于如何与 Cypress 集成的 Auth0 has a guide,但它不使用此 SDK,而是使用 SPA SDK。该指南还使用了自定义登录表单,我在其中使用了 LockUI。
需要注意的一点是,我没有使用后端进行身份验证(就像在大多数示例中一样)。我按照官方建议使用 loginWithRedirect
登录。
答案 0 :(得分:1)
经过 Auth0 团队的一些调查和帮助,我成功地完成了这项工作。
这是我使用的代码:
Cypress.Commands.add("login", () => {
cy.clearLocalStorage();
const email = "";
const password = "";
const client_id = "";
const client_secret = "";
const audience = "";
const scope = "";
cy.request({
method: "POST",
url: "",
body: {
grant_type: "password",
username: email,
password,
audience,
scope,
client_id,
client_secret,
},
}).then(({ body: { access_token, expires_in, id_token, token_type } }) => {
cy.window().then((win) => {
win.localStorage.setItem(
`@@auth0spajs@@::${client_id}::${audience}::${scope}`,
JSON.stringify({
body: {
client_id,
access_token,
id_token,
scope,
expires_in,
token_type,
decodedToken: {
user: JSON.parse(
Buffer.from(id_token.split(".")[1], "base64").toString("ascii")
),
},
audience,
},
expiresAt: Math.floor(Date.now() / 1000) + expires_in,
})
);
cy.reload();
});
});
});
您必须确保您传入的配置完全与您在 Auth0 Provider 中使用的配置相同。
有一次要注意的是,我还使用了刷新令牌。如果是这种情况,请确保将 offline_access
添加到您的范围。
我有一个公共存储库可以下载一个有效的解决方案 - https://github.com/charklewis/auth0-cypress。
答案 1 :(得分:0)
Cypress Real World App 中有一个示例,它是一个支付应用程序,用于演示赛普拉斯测试方法、模式和工作流程的实际使用情况,此外还有一个 Auth0 Authentication Testing Strategies Guide 详细说明了 Auth0 中的更改应用程序和 Cypress Real World App。