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

采用Clerk认证的网站在Cypress测试中登录页返回401问题

解决Cypress测试Clerk认证网站时的401问题

问题分析

你的网站采用Clerk认证,在Cypress测试时登录页返回401,但无痕窗口中出现401后会自动发起新请求并通过重定向完成认证。从响应头可以明确原因:

  • x-clerk-auth-reason: uat-missing:缺少用户认证令牌(UAT)
  • x-clerk-auth-status: interstitial:Clerk需要加载中间页完成认证流程

无痕窗口会自动处理这类重定向逻辑,但Cypress的自动化环境需要手动配置才能适配该流程。

解决方案

1. 用Clerk测试API生成会话(推荐)

绕过前端登录流程,直接通过Clerk后端API创建测试用户并生成有效会话,将会话令牌注入Cypress的Cookie中:

// 在测试文件的before钩子或cypress/support/e2e.js中
before(() => {
  // 创建测试用户
  cy.request({
    method: 'POST',
    url: 'https://api.clerk.com/v1/users',
    headers: {
      'Authorization': `Bearer ${Cypress.env('CLERK_SECRET_KEY')}`,
      'Content-Type': 'application/json'
    },
    body: {
      email_addresses: [{email: 'test-user@example.com'}],
      password: 'test-password-123'
    }
  }).then((userRes) => {
    const userId = userRes.body.id;
    // 生成用户会话
    return cy.request({
      method: 'POST',
      url: `https://api.clerk.com/v1/users/${userId}/sessions`,
      headers: {
        'Authorization': `Bearer ${Cypress.env('CLERK_SECRET_KEY')}`
      }
    });
  }).then((sessionRes) => {
    const sessionId = sessionRes.body.id;
    // 设置Clerk会话Cookie(根据网站实际配置调整Cookie名称)
    cy.setCookie('__session', sessionId, {
      domain: 'your-domain.com',
      secure: true,
      httpOnly: true
    });
  });
});

2. 配置Cypress支持第三方Cookie与重定向

Clerk认证依赖第三方Cookie,且需要处理interstitial重定向,修改cypress.config.js添加浏览器启动参数:

const { defineConfig } = require('cypress');

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('before:browser:launch', (browser, launchOptions) => {
        if (browser.family === 'chromium' && browser.name !== 'electron') {
          // 禁用SameSite默认策略,允许第三方Cookie
          launchOptions.args.push('--disable-features=SameSiteByDefaultCookies,CookiesWithoutSameSiteMustBeSecure');
          return launchOptions;
        }
      });
    },
    baseUrl: 'https://your-website.com',
  },
});

测试中等待重定向完成:

cy.visit('/login');
// 等待跳转到登录后的目标页面
cy.url().should('include', '/dashboard');

3. 拦截401请求并手动触发重定向

如果上述方法无效,可拦截401响应并主动触发后续流程:

cy.intercept('GET', '/login', (req) => {
  req.continue((res) => {
    if (res.statusCode === 401 && res.headers['x-clerk-auth-status'] === 'interstitial') {
      // 跳转到Clerk中间页完成认证
      cy.visit(res.headers.location || '/clerk-interstitial');
    }
  });
});

cy.visit('/login');

内容的提问来源于stack exchange,提问作者froblesmartin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 12:22:48