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

如何在scheb/2fa扩展中实现邮箱验证码重新发送功能?

实现邮箱验证码重发功能步骤

1. 添加路由与访问控制

首先修改config/packages/security.yaml的access_control部分,新增重发路由的权限规则:

access_control:
    # 新增这一行,放在原有/2fa规则后面即可
    - { path: '^/2fa/resend', roles: IS_AUTHENTICATED_2FA_IN_PROGRESS }
    - { path: '^/2fa', roles: IS_AUTHENTICATED_2FA_IN_PROGRESS }
    # 其余原有规则保持不变
    - { path: '^/login', roles: IS_AUTHENTICATED_ANONYMOUSLY }
    # ... 其余规则省略

然后在config/routes.yaml中添加重发路由配置:

2fa_resend:
    path: /2fa/resend
    controller: App\Controller\TwoFactorController::resend

2. 实现重发逻辑控制器

新建src/Controller/TwoFactorController.php文件,代码如下:

<?php

namespace App\Controller;

use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Email\Generator\CodeGeneratorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class TwoFactorController extends AbstractController
{
    public function resend(CodeGeneratorInterface $codeGenerator, TokenStorageInterface $tokenStorage): RedirectResponse
    {
        $user = $tokenStorage->getToken()?->getUser();
        // 调用官方服务生成新验证码并发送到用户邮箱
        $codeGenerator->generateAndSend($user);
        // 添加闪信提示发送结果,重定向回2FA验证页
        $this->addFlash('success', '新的验证码已发送到您的绑定邮箱');
        return $this->redirectToRoute('2fa_login');
    }
}

3. 2FA表单添加重发入口

打开你配置的security/2fa_form.html.twig模板,在表单合适位置添加重发按钮:

{# 可放在验证码输入框下方位置 #}
<a href="{{ path('2fa_resend') }}" class="resend-btn">重新发送验证码</a>

{# 可选:添加前端防频繁发送倒计时 #}
{# <a href="{{ path('2fa_resend') }}" class="resend-btn" id="resendBtn">重新发送验证码</a>
<script>
const btn = document.getElementById('resendBtn');
btn.addEventListener('click', e => {
    e.preventDefault();
    let count = 60;
    btn.innerText = `${count}秒后可重新发送`;
    btn.style.pointerEvents = 'none';
    const timer = setInterval(() => {
        count--;
        btn.innerText = `${count}秒后可重新发送`;
        if (count <= 0) {
            clearInterval(timer);
            btn.innerText = '重新发送验证码';
            btn.style.pointerEvents = 'auto';
        }
    }, 1000);
    window.location.href = btn.getAttribute('href');
});
</script> #}

4. 功能验证

用户在2FA验证页点击重发按钮后,系统会自动生成新的6位验证码发送到用户绑定邮箱,原有验证码直接失效,用户输入新收到的验证码即可完成双因素认证。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 23:42:03