应用路由器API路由中的NextAuth获取会话

drkbr07n  于 11个月前  发布在  其他
关注(0)|答案(2)|浏览(109)

我正在使用NextAuth和Next.js的App Router。我已经在我的/app/API文件夹中创建了一个API路由。但是,我无法检索与请求对应的会话。
下面是我的API路由,我使用get(url)方法调用它:

export async function GET(req: NextApiRequest) {
    const session = await getServerSession(req);

    console.log(session);

    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}

字符串
然而,当它运行时,我在服务器上得到以下错误:

[next-auth][error][JWT_SESSION_ERROR] 
https://next-auth.js.org/errors#jwt_session_error Invalid Compact JWE {
  message: 'Invalid Compact JWE',
  stack: 'JWEInvalid: Invalid Compact JWE\n' +
    '    at compactDecrypt (webpack-internal:///(rsc)/./node_modules/jose/dist/node/cjs/jwe/compact/decrypt.js:18:15)\n' +
    '    at jwtDecrypt (webpack-internal:///(rsc)/./node_modules/jose/dist/node/cjs/jwt/decrypt.js:10:61)\n' +
    '    at Object.decode (webpack-internal:///(rsc)/./node_modules/next-auth/jwt/index.js:44:52)\n' +
    '    at async Object.session (webpack-internal:///(rsc)/./node_modules/next-auth/core/routes/session.js:25:34)\n' +
    '    at async AuthHandler (webpack-internal:///(rsc)/./node_modules/next-auth/core/index.js:161:37)\n' +
    '    at async getServerSession (webpack-internal:///(rsc)/./node_modules/next-auth/next/index.js:126:21)\n' +
    '    at async GET (webpack-internal:///(rsc)/./app/api/newwatchlist/route.ts:11:21)\n' +
    '    at async D:\\Coding Projects\\market-pulse\\node_modules\\next\\dist\\compiled\\next-server\\app-route.runtime.dev.js:6:61856',
  name: 'JWEInvalid'
}


session为null。
我无法访问响应对象来传递普通的getServerSession(req, res, authOptions)方法(据我所知)。
如何使用Next的新API路由获取与HTTP请求对应的会话?
注意:我正在使用MongoDB适配器。

**更新:**我也尝试过将res: NextApiResponse作为参数,然后使用const session = await getServerSession(req, res, authOptions);获取会话。但这会导致TypeError: res.getHeader is not a function

9lowa7mx

9lowa7mx1#

我猜你没有传递jwt相关信息给getServerSession

// you just passed req
// you have to define authOptions
const session = await getServerSession(req, res, authOptions)

字符串

rkkpypqq

rkkpypqq2#

原来我只需要传递authOptions,而不是res或req:const session = await getServerSession(authOptions);
然后,我的整个函数看起来像这样:

export async function GET(req: NextApiRequest) {
    const session = await getServerSession(authOptions);  
    console.log(session);
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 }; 
}

字符串

相关问题