如何在Cypress测试中设置Azure App Service的AppServiceAuthSession Cookie
解决Cypress测试Azure App Service EasyAuth保护的SPA登录问题
核心思路
通过获取有效的AppServiceAuthSession Cookie并在Cypress测试中预先设置,绕过自动重定向登录流程,无需修改生产代码集成MSAL/ADAL。
步骤1:获取有效AppServiceAuthSession Cookie
有两种可靠方式获取:
手动提取(快速测试用)
- 正常登录SPA,打开浏览器开发者工具(F12)
- 切换到
Application标签页,展开Cookies,找到你的App Service域名 - 复制
AppServiceAuthSession的以下属性:值、域名、路径、Secure状态、HttpOnly状态
Cypress请求模拟(自动化用)
利用Azure AD的ROPC(资源所有者密码凭据)模式直接获取令牌,再向App Service认证端点换取Cookie:// 1. 向Azure AD获取访问令牌 cy.request({ method: 'POST', url: 'https://login.microsoftonline.com/{你的租户ID}/oauth2/v2.0/token', form: true, body: { client_id: '你的App Service应用注册ID', scope: 'https://{你的App Service域名}/user_impersonation offline_access', username: '测试账号邮箱', password: '测试账号密码', grant_type: 'password' } }).then((tokenResponse) => { // 2. 用令牌向App Service换取Auth Session Cookie cy.request({ method: 'GET', url: 'https://{你的App Service域名}/.auth/me', headers: { 'Authorization': `Bearer ${tokenResponse.body.access_token}` } }) }) // 执行完以上请求后,Cypress会自动存储返回的AppServiceAuthSession Cookie注意:ROPC模式需要在Azure AD应用注册中启用"允许公共客户端流",且仅适用于测试环境,生产环境不推荐。
步骤2:在Cypress测试中设置Cookie
如果用手动提取的方式,在测试用例开头添加以下代码:
// 需在cypress.config.js中设置chromeWebSecurity: false,否则无法设置HttpOnly Cookie cy.setCookie('AppServiceAuthSession', '复制的Cookie值', { domain: '你的App Service域名', path: '/', secure: true, httpOnly: true, sameSite: 'None' // 根据实际Cookie的SameSite属性调整 })
关键配置注意
在cypress.config.js中确保以下配置,避免跨域和Cookie权限问题:
module.exports = defineConfig({ e2e: { chromeWebSecurity: false, experimentalModifyObstructiveThirdPartyCode: true } })
内容的提问来源于stack exchange,提问作者maddy
相关产品推荐
相关产品推荐

