使用 iron-session 与 NextJS 和新的应用程序路由器

huangapple go评论98阅读模式
英文:

using iron-session with NextJS and the new app router

问题

抱歉我的无知...我对会话cookie和身份验证没有完全掌握,这就是为什么我正在构建一个东西...以理解,然后做得更好...

无论如何,我正试图在我的nextJS应用程序上启用会话cookie,并且正在移植来自iron session的示例代码...然而,iron session的示例使用了页面路由,而我在我的应用程序中没有使用。

例如,这是iron sessions示例中的登录路由:

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文档,但在将页面路由迁移到应用程序路由方面没有找到太多信息。有什么建议或想法吗?

我希望这个问题表达得清楚,如果不清楚的话,请随时提出澄清性问题。

一如既往,感谢!
Chris Roode

英文:

Pardon my ignorance...I don't have a 100% grasp of session cookies, and authentication, which is why I am building something...to understand, then to do better...

Anyway, I am trying to get session cookies going on my nextJS app, and I am porting in the sample code from iron session...however, the examples of iron session use the pages router, which I am not using in my application.

For example, here's the login route from iron sessions examples:

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);

You can see the full code I'm referencing at: https://github.com/vvo/iron-session
follow /examples/next.js/

Right now, the problem I'm facing is that the app router in nextJS wants a POST() or GET() function for it to work properly, and I dont' have a complete grasp of how withIronSessionApiRoute() is wrapping itself around the routing.

I've looked extensively at the nextJS documentation around this, but haven't found much in migrating pages router to app router. Any suggestions or thoughts?

I hope this question comes across cleary, if not, feel free to ask clarifying questions.

As always, thanks!
Chris Roode

答案1

得分: 1

I recently migrated an application to the app router, the withIronSessionSsr method is just a wrapper for easier use, to achieve the same functionality you can just leverage the low level seal/unseal methods. Something like this (in a server component):

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>;
}

Creating the session can be tricky since you need to set the encrypted session with a cookie header either in a route handler or a middleware.

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}` },
  });
}

Credits: https://github.com/vvo/iron-session/issues/594#issuecomment-1638964195

英文:

I recently migrated an application to the app router, the withIronSessionSsr method is just a wrapper for easier use, to achieve the same functionality you can just leverage the low level seal/unseal methods. Something like this (in a server component):

import { unsealData } from &#39;iron-session/edge&#39;;
import { cookies } from &#39;next/headers&#39;;

export default async function Page() {
  const cookieStore = cookies();

  const encryptedSession = cookieStore.get(&#39;name-of-your-cookie&#39;)?.value;

  const session = encryptedSession
    ? await unsealData(encryptedSession, {
        password: &#39;your-password&#39;,
      })
    : null;

  return &lt;div&gt;{session ? session.some_value : &#39;not authenticated&#39;}&lt;/div&gt;;
}

Creating the session can be tricky since you need to set the encrypted session with a cookie header either in a route handler or a middleware.

import { sealData } from &#39;iron-session/edge&#39;;

// endpoint to log in a user
export async function POST() {
  const session = JSON.stringify({
    userId: 1,
    name: &#39;john doe&#39;,
  });

  const encryptedSession = sealData(session, {
    password: &#39;your-password&#39;,
  });

  return new Response(&#39;ok&#39;, {
    status: 200,
    headers: { &#39;Set-Cookie&#39;: `name-of-your-cookie=${encryptedSession}` },
  });
}

Credits: https://github.com/vvo/iron-session/issues/594#issuecomment-1638964195

huangapple
  • 本文由 发表于 2023年5月29日 20:25:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76357370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定