You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress测试中设置Azure App Service的AppServiceAuthSession Cookie

解决Cypress测试Azure App Service EasyAuth保护的SPA登录问题

核心思路

通过获取有效的AppServiceAuthSession Cookie并在Cypress测试中预先设置,绕过自动重定向登录流程,无需修改生产代码集成MSAL/ADAL。

有两种可靠方式获取:

  • 手动提取(快速测试用)

    1. 正常登录SPA,打开浏览器开发者工具(F12)
    2. 切换到Application标签页,展开Cookies,找到你的App Service域名
    3. 复制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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:10:25