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

为何Laravel Fortify会对API请求返回重定向?

解决Laravel Fortify API认证失败时的重定向问题

1. 确认请求头有效性

先确保客户端请求确实携带了 Accept: application/json 头——Laravel依赖这个标识判断是否返回JSON响应而非重定向。可以通过Postman、浏览器调试工具或服务器日志验证请求头是否正确传递。

2. 自定义Fortify认证动作

重写Fortify默认的认证逻辑,针对JSON请求返回对应错误响应:

  • 创建/修改自定义登录动作类 app/Actions/Fortify/AttemptToAuthenticate.php:
<?php

namespace App\Actions\Fortify;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Fortify\Actions\AttemptToAuthenticate as FortifyAttemptToAuthenticate;

class AttemptToAuthenticate extends FortifyAttemptToAuthenticate
{
    public function handle(Request $request, $next)
    {
        // 已登录状态下的JSON请求直接返回错误
        if (Auth::check() && $request->wantsJson()) {
            return response()->json([
                'message' => '用户已登录'
            ], 403);
        }

        return parent::handle($request, $next);
    }
}
  • 在 config/fortify.php 中替换默认动作:
'actions' => [
    // ...其他配置
    'login' => App\Actions\Fortify\AttemptToAuthenticate::class,
],

3. 全局拦截认证重定向

在 app/Providers/FortifyServiceProvider.php 的 boot 方法中添加全局处理逻辑,覆盖所有认证场景的重定向行为:

use Laravel\Fortify\Fortify;
use Laravel\Fortify\Http\Requests\LoginRequest;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

public function boot()
{
    // ...其他Fortify配置

    // 自定义认证逻辑
    Fortify::authenticateUsing(function (LoginRequest $request) {
        $user = User::where('email', $request->email)->first();

        if ($user && Hash::check($request->password, $user->password)) {
            if (Auth::check()) {
                return $request->wantsJson() 
                    ? response()->json(['message' => '用户已登录'], 403)
                    : abort(403, '用户已登录');
            }
            return $user;
        }

        return null;
    });

    // 自定义认证失败响应
    Fortify::loginView(function () {
        return request()->wantsJson()
            ? response()->json(['message' => '认证失败'], 401)
            : view('auth.login');
    });
}

4. 检查路由中间件配置

确保Fortify路由注册在API路由文件中,使用 api 中间件组而非 web 中间件:
在 routes/api.php 中添加:

use Laravel\Fortify\Fortify;

Fortify::routes();

完成以上配置后,重新测试已登录状态下的登录请求,应返回JSON格式的错误信息,而非重定向头。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 02:05:05