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

如何在Rails 7中仅在开发及测试环境启用2FA前置操作?

解决Rails 7中仅在开发/测试环境启用自定义2FA的问题

一、限制2FA校验仅在指定环境生效

你可以给before_action添加环境判断条件,让2FA的校验逻辑只在开发和测试环境中执行:

class ApplicationController < ActionController::Base
  # 仅在开发/测试环境触发2FA校验
  before_action :check_two_factor_authentication, if: -> { Rails.env.development? || Rails.env.test? }

  private

  def check_two_factor_authentication
    return true unless session[:challenge_id]

    redirect_to two_factor_path
  end
end

二、关于check_authentication的说明

Devise的核心回调方法里并没有check_authentication这个方法,这应该是你复制代码时遗留的冗余配置。既然你的应用中没有定义这个方法,直接去掉except: :check_authentication即可,避免触发未定义方法的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 11:01:57