Laravel Inertia登录后弹出iframe而非跳转至回调地址求助
问题:Laravel Passport授权码模式下登录后跳转异常(iframe模态框而非回调地址)
环境信息
- 客户端:Next.js,部署地址
http://localhost:3005 - 回调地址:
http://localhost:3005/auth/callback - Laravel服务端:部署地址
http://localhost:5001
问题现象
使用Laravel Passport的Authorization Code Grant授权模式,引导用户完成登录后,Inertia并未跳转至指定的回调地址,而是弹出iframe模态框加载内容。
相关代码
Next.js回调页面(http://localhost:3005/auth/callback)
import React, { useEffect } from "react"; import { useRouter } from "next/router"; import axios from "axios"; const getToken = async (code) => { try { const response = await axios.post( `${process.env.NEXT_PUBLIC_OAUTH_AUTH_SERVER}/oauth/token`, { grant_type: "authorization_code", client_id: process.env.NEXT_PUBLIC_OAUTH_CLIENT_ID, client_secret: process.env.NEXT_PUBLIC_OAUTH_CLIENT_SECRET, redirect_uri: process.env.NEXT_PUBLIC_OAUTH_CLIENT_REDIRECT, code: code, } ); return response; } catch (error) { return error; } }; const callback = () => { const router = useRouter(); const { code } = router.query; useEffect(() => { if (code) { getToken(code) .then((response) => { console.log(response); }) .catch((error) => { console.log(error); }); } }, [code]); return <div>Logging you in ....</div>; }; export default callback;
Laravel端登录控制器(app\Http\Auth\AuthenticatedSessionController)
public function store(LoginRequest $request): RedirectResponse { $request->authenticate(); $request->session()->regenerate(); $intendedUrl = session('url.intended'); if ($intendedUrl) { return redirect($intendedUrl); } return redirect()->intended(RouteServiceProvider::HOME); }
解决方案
核心原因
Inertia默认会拦截重定向请求,当重定向目标为跨域地址(此处Next.js与Laravel端口不同,属于跨域场景)时,Inertia会自动以iframe模态框形式加载目标地址,而非触发浏览器全页面跳转——这与Authorization Code Grant模式要求的全页面跳转到回调地址逻辑冲突。
修复步骤
修改Laravel登录控制器的store方法,添加X-Inertia: false响应头,强制Inertia不处理该重定向,让浏览器执行原生全页面跳转:
public function store(LoginRequest $request): RedirectResponse { $request->authenticate(); $request->session()->regenerate(); $intendedUrl = session('url.intended'); if ($intendedUrl) { return redirect($intendedUrl)->header('X-Inertia', 'false'); } return redirect()->intended(RouteServiceProvider::HOME)->header('X-Inertia', 'false'); }
额外检查项
- 确认Laravel Passport客户端配置中的回调地址与
http://localhost:3005/auth/callback完全一致,无拼写或端口错误; - 确保Laravel的CORS配置允许
http://localhost:3005域名的请求; - 客户端发起授权请求时,需让用户直接访问Laravel的Passport授权路由(如
/oauth/authorize),而非通过Inertia的axios请求触发,避免Inertia提前拦截流程。
内容的提问来源于stack exchange,提问作者desh
相关产品推荐
相关产品推荐

