Next.js API调用认证不生效问题求助
问题原因分析
你的API认证不生效的核心问题在于**auth.config.ts中的authorized回调逻辑没有对API路径做登录校验**。当前的回调只针对/dashboard路径做了权限控制,其他所有路径(包括/api/...)都会直接返回true,允许未认证请求访问。
看你当前的authorized回调:
authorized({ auth, request: { nextUrl } }) { const isLoggedIn = !!auth?.user; const isOnDashboard = nextUrl.pathname.startsWith('/dashboard'); if (isOnDashboard) { if (isLoggedIn) return true; return false; // Redirect unauthenticated users to login page } else if (isLoggedIn) { return Response.redirect(new URL('/dashboard', nextUrl)); } return true; // 这里是关键!所有非dashboard、非已登录的路径都直接通过 }
对于API请求,因为它既不是/dashboard开头,且未登录时不会进入else if (isLoggedIn)分支,所以最终会执行return true,直接允许访问。
解决方案
修改authorized回调,增加对API路径的判断,要求所有API请求必须携带有效的认证信息,并且针对API请求返回401(未授权)而不是重定向(重定向是给页面跳转用的,API场景不合适)。
修改后的auth.config.ts代码:
import type { NextAuthConfig } from 'next-auth'; export const authConfig = { pages: { signIn: '/login', }, callbacks: { authorized({ auth, request: { nextUrl } }) { const isLoggedIn = !!auth?.user; const isOnDashboard = nextUrl.pathname.startsWith('/dashboard'); const isApiRoute = nextUrl.pathname.startsWith('/api/'); // 处理API路由:必须登录,否则返回401 if (isApiRoute) { if (isLoggedIn) return true; // 对API请求返回401,而不是重定向 return Response.json({ error: 'Unauthorized' }, { status: 401 }); } // 原有的dashboard和页面跳转逻辑 if (isOnDashboard) { if (isLoggedIn) return true; return false; // 重定向到登录页 } else if (isLoggedIn) { return Response.redirect(new URL('/dashboard', nextUrl)); } return true; }, }, providers: [], // Add providers with an empty array for now } satisfies NextAuthConfig;
关键说明
- 新增
isApiRoute判断,识别所有/api/开头的请求 - 对于API请求,未登录时返回
Response.json带401状态码,而不是return false(后者会触发页面重定向,不符合API的交互逻辑) - 保留原有的页面路由权限逻辑,不影响前端页面的跳转行为
验证效果
修改后重新启动服务,再执行curl命令:
curl -v -X POST 'http://localhost:3000/api/my-api'
此时应该返回401 Unauthorized,携带认证信息的请求才能正常返回200。
内容的提问来源于stack exchange,提问作者hudac
相关产品推荐
相关产品推荐

