使用Cypress测试WebAuthn注册遇publickey-credentials-create禁用问题
解决Cypress中WebAuthn注册测试的Feature Policy限制问题
1. 调整浏览器启动参数
在cypress.config.ts中添加Chrome命令行参数,强制解除WebAuthn相关特性的策略限制:
import { defineConfig } from 'cypress'; export default defineConfig({ e2e: { setupNodeEvents(on, config) { on('before:browser:launch', (browser, launchOptions) => { if (browser.family === 'chromium' && browser.name !== 'electron') { // 解除WebAuthn特性的策略限制 launchOptions.args.push('--disable-features=WebAuthenticationPolicyFeature'); // 强制启用PublicKeyCredential特性 launchOptions.args.push('--enable-features=PublicKeyCredential'); return launchOptions; } }); }, chromeWebSecurity: false, experimentalModifyObstructiveThirdPartyCode: true, }, });
2. 手动设置目标帧的Feature Policy
如果浏览器参数调整无效,在测试用例中通过CDP命令直接给目标帧设置允许WebAuthn操作的策略:
describe('WebAuthn Registration Test', () => { beforeEach(() => { // 添加虚拟CTAP2认证器 cy.wrap(Cypress.automation('remote:debugger:protocol', { command: 'WebAuthn.addVirtualAuthenticator', params: { options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true } } })).as('authenticator'); }); afterEach(() => { // 清理虚拟认证器 cy.get('@authenticator').then(auth => { cy.wrap(Cypress.automation('remote:debugger:protocol', { command: 'WebAuthn.removeVirtualAuthenticator', params: { authenticatorId: (auth as any).authenticatorId } })); }); }); it('should complete WebAuthn registration', () => { cy.visit('/your-registration-path').then(() => { // 获取当前页面主帧ID cy.wrap(Cypress.automation('remote:debugger:protocol', { command: 'Page.getFrameTree' })) .then(frameTree => { const mainFrameId = frameTree.frameTree.frame.id; // 设置主帧的Feature Policy,允许WebAuthn相关操作 return cy.wrap(Cypress.automation('remote:debugger:protocol', { command: 'Frame.setFeaturePolicy', params: { frameId: mainFrameId, policy: "publickey-credentials-create *; publickey-credentials-get *" } })); }); // 触发注册流程 cy.get('[data-testid="register-button"]').click(); // 模拟用户验证通过 cy.get('@authenticator').then(auth => { cy.wrap(Cypress.automation('remote:debugger:protocol', { command: 'WebAuthn.setUserVerified', params: { authenticatorId: (auth as any).authenticatorId, isUserVerified: true } })); }); // 验证注册成功状态 cy.get('[data-testid="registration-success"]').should('be.visible'); }); }); });
3. 调试验证Feature Policy状态
如果问题仍存在,可添加调试步骤确认帧的Feature Policy是否已更新:
cy.window().then(win => { // 打印当前帧允许的所有特性 console.log(win.document.featurePolicy.allowedFeatures()); });
检查输出中是否包含publickey-credentials-create和publickey-credentials-get。
内容的提问来源于stack exchange,提问作者Myrto Pirli
相关产品推荐
相关产品推荐

