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

Laravel Fortify REST API环境下邮箱验证问题咨询

Laravel Fortify REST API 邮箱验证问题解决方案

你完全可以直接使用Fortify自带的邮箱验证功能,不需要完全自定义控制器,问题出在Fortify默认逻辑适配web端场景,需要针对REST API做两处关键调整:

1. 覆盖邮箱验证成功后的响应逻辑

在FortifyServiceProvider中绑定自定义的VerifyEmailResponse,替换默认的重定向行为为JSON响应:

// app/Providers/FortifyServiceProvider.php
use Laravel\Fortify\Contracts\VerifyEmailResponse as VerifyEmailResponseContract;
use App\Http\Responses\VerifyEmailResponse;

public function register()
{
    $this->app->bind(VerifyEmailResponseContract::class, VerifyEmailResponse::class);
}

然后创建自定义响应类:

// app/Http/Responses/VerifyEmailResponse.php
use Laravel\Fortify\Contracts\VerifyEmailResponse as VerifyEmailResponseContract;

class VerifyEmailResponse implements VerifyEmailResponseContract
{
    public function toResponse($request)
    {
        return response()->json([
            'message' => '邮箱验证成功'
        ], 200);
    }
}

2. 修复「route [login] not defined」错误

Fortify验证邮箱时,若检测到用户未登录,默认会重定向到web端的login路由。针对API场景,修改认证中间件的响应逻辑:

// app/Http/Middleware/Authenticate.php
protected function redirectTo($request)
{
    if (!$request->expectsJson()) {
        return route('login');
    }
    // API请求返回JSON错误
    return response()->json(['message' => '请先登录'], 401);
}

同时确保Fortify的邮箱验证路由使用API中间件组:

// app/Providers/FortifyServiceProvider.php
public function boot()
{
    Fortify::routes(function () {
        Route::group([
            'middleware' => ['api'],
        ], function () {
            Fortify::verifyEmail();
        });
    });
}

3. 适配API验证链接格式

在config/fortify.php中配置API可用的验证链接生成逻辑:

'emailVerificationUrl' => function ($notifiable) {
    return url('/api/email/verify/'.$notifiable->getKey().'/'.$notifiable->getEmailVerificationToken().'?'.http_build_query([
        'expires' => now()->addMinutes(60)->getTimestamp(),
        'signature' => hash_hmac('sha256', $notifiable->getKey().'|'.$notifiable->getEmailVerificationToken(), config('app.key')),
    ]));
},

完成以上配置后,就能直接使用Fortify自带的VerifyEmailController实现REST API场景下的邮箱验证,无需自行编写完整控制器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 14:02:33