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

如何扩展Clearance后门功能以支持双因素认证(2FA)

如何在Clearance Backdoor中集成双因素认证(2FA)测试

完全可以通过Hook Clearance的Backdoor功能,在测试登录时自动设置2FA验证状态,无需手动输入验证码。以下是具体实现方案:

核心思路

Clearance的Backdoor是通过直接设置会话完成登录的测试快捷方式,我们可以扩展这一逻辑,在登录后附加2FA的已验证标记,模拟用户完成2FA流程后的状态。

具体实现方式

1. 自定义扩展Backdoor方法(推荐)

无需修改Clearance源码,在测试辅助文件(如test/support/clearance_backdoor_2fa.rb)中添加扩展:

module ClearanceBackdoorWith2FA
  def sign_in_as(user)
    # 先执行Clearance原生的Backdoor登录逻辑
    super(user)
    # 根据你的2FA实现,设置已验证状态
    # 示例1:会话存储验证标记
    session[:two_factor_authenticated] = true
    # 示例2:更新用户模型的验证时间字段
    user.update!(two_factor_verified_at: Time.current)
  end
end

# 在集成测试类中引入该模块
class ActionDispatch::IntegrationTest
  include ClearanceBackdoorWith2FA
end

2. 直接配置Clearance的登录钩子

如果需要更深度的集成,可在测试环境配置文件(config/environments/test.rb)中重写Clearance的登录逻辑:

Clearance.configure do |config|
  config.sign_in = lambda do |session, user|
    # 保留原生会话设置
    session[:user_id] = user.id
    # 附加2FA验证状态
    session[:two_factor_authenticated] = true
    # 替换为你项目中标记2FA通过的具体逻辑
  end
end

3. RSpec测试适配

若使用RSpec,可在spec/support/clearance.rb中重写登录方法:

RSpec.configure do |config|
  config.include Clearance::Testing::Helpers

  def sign_in(user)
    super(user)
    # 设置2FA已验证状态
    session[:two_factor_authenticated] = true
  end
end

注意事项

  • 确保你的2FA逻辑依赖会话或用户模型字段判断验证状态,这样才能在测试中直接设置。
  • 所有扩展代码仅在测试环境加载,避免影响生产环境。
  • 若使用第三方2FA工具,需对应调整设置验证状态的具体代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 08:01:55