请原谅我的无知...我没有 100% 掌握会话 cookie 和身份验证,这就是为什么我正在构建一些东西...理解,然后做得更好...
无论如何,我正在尝试让会话cookie在我的nextJS应用程序上运行,并且我正在从iron session中移植示例代码...但是,iron session的示例使用页面路由器,我没有在我的应用程序中使用它.
例如,以下是来自 Iron 会话示例的登录路线:
import { Octokit } from "octokit";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "lib/session";
const octokit = new Octokit();
export default withIronSessionApiRoute(async (req, res) => {
const { username } = await req.body;
try {
const {
data: { login, avatar_url },
} = await octokit.rest.users.getByUsername({ username });
const user = { isLoggedIn: true, login, avatarUrl: avatar_url };
req.session.user = user;
await req.session.save();
res.json(user);
} catch (error) {
res.status(500).json({ message: error.message });
}
}, sessionOptions);
您可以在以下位置查看我引用的完整代码:https://github.com/vvo/iron-session 关注 /examples/next.js/
现在,我面临的问题是 nextJS 中的应用程序路由器需要 POST() 或 GET() 函数才能正常工作,而我不完全掌握 withIronSessionApiRoute() 是如何包装自身的路由。
我已经广泛地查看了与此相关的 nextJS 文档,但在将页面路由器迁移到应用程序路由器方面没有找到太多内容。有什么建议或想法吗?
我希望这个问题能被清楚地表达出来,如果没有,请随时提出澄清问题。
一如既往,谢谢! 克里斯·鲁德
我最近将一个应用程序迁移到应用程序路由器,withIronSessionSsr 方法只是一个更容易使用的包装器,要实现相同的功能,您只需利用低级密封/解封方法即可。像这样的东西(在服务器组件中):
import { unsealData } from 'iron-session/edge';
import { cookies } from 'next/headers';
export default async function Page() {
const cookieStore = cookies();
const encryptedSession = cookieStore.get('name-of-your-cookie')?.value;
const session = encryptedSession
? await unsealData(encryptedSession, {
password: 'your-password',
})
: null;
return <div>{session ? session.some_value : 'not authenticated'}</div>;
}
创建会话可能很棘手,因为您需要在路由处理程序或中间件中使用 cookie 标头设置加密会话。
import { sealData } from 'iron-session/edge';
// endpoint to log in a user
export async function POST() {
const session = JSON.stringify({
userId: 1,
name: 'john doe',
});
const encryptedSession = sealData(session, {
password: 'your-password',
});
return new Response('ok', {
status: 200,
headers: { 'Set-Cookie': `name-of-your-cookie=${encryptedSession}` },
});
}
鸣谢:https://github.com/vvo/iron-session/issues/594#issuecomment-1638964195
好久不见,是时候更新这个问题了。这不再是问题,因为 iron-session 现在支持 next.js 的应用程序路由器。它也有详细记录!