在 next-auth 中将来自 API 的 JWT 令牌存储在哪里

use*_*311 4 javascript reactjs next.js next-auth

我按照一些在线教程在 next-auth 中实现了这个

import NextAuth from "next-auth"
import Providers from "next-auth/providers";
const https = require('https');

export default NextAuth({
  providers: [
    Providers.Credentials({
      name: 'Credentials',
      credentials: {
        email: { label: "Email", type: "email" },
        password: {  label: "Password", type: "password" }
      },
      async authorize(credentials) {
        const url = 'https://localhost/auth';

        const httpsAgent = new https.Agent({
          rejectUnauthorized: false,
        });

        const res = await fetch(url, {
          method: 'POST',
          body: JSON.stringify(credentials),
          agent: httpsAgent,
          headers: {
            "Content-Type": "application/json"
          }
        })
        const user = await res.json();

        if (res.ok && user) {
          return user;
        } else {
          return null;
        }
      }
    }),
    // ...add more providers here
  ],
  callbacks: {
    async jwt(token, user, account, profile, isNewUser) {
      if (user?.type) {
        token.status = user.type
      }
      if (user?.username) {
        token.username = user.username;
      }

      return token
    },

    async session(session, token) {
      session.type = token.type;
      session.username = token.username;
      return session
    }
  }
})

Run Code Online (Sandbox Code Playgroud)

相当标准。https://localhost/auth 返回一个像这样的对象(我现在称之为用户)

{
  token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJpYXQiOjE2MzY0MTE4NjEsImV4cCI6MTYzNjQxNTQ2MSwicm9sZXMiOlsiUk9MRV9VU0VSIl0sInVzZXJuYW1lIjoiZXJuYTM5QHdlYmVyLmNvbSJ9.Abenx1GhB-_d9LVpLfa2NYp62Lbw6U65EUQowA0jA_aykx1m-BlBR_YBcL4XIJsknJ99NN8Ees4Zxdsphfhjs7du4TR2MgTITHYy-BYjBX9CsluVSBpm-L7c-oK5vu70eumAy1ixy5MKOTN2EQYCm65RszSheIwZ4LN8vSuzxzZuLszRG9nbpauiHDpYCeLrNeNkz4lhTicfWkdPafR8vhqt4MIeCl-kxbMqc35UNmglzE7n-b9zVh4OhU7bSCoPKZySL5c4GSf7UFFD-mXIe6s9b4qYSXJuLpdspFJSgP7UoEGP1gh8fTb5MDZREYyZOpK3BMU8EdwokngVR9zrbw'
}
Run Code Online (Sandbox Code Playgroud)

我想知道如何存储此令牌以便在进一步调用我的 API 时使用。我可以看到会话回调中的令牌对象是

{ iat: 1636411862, exp: 1639003862 }
Run Code Online (Sandbox Code Playgroud)

所以 next-aut 不为我做这个。我应该在会话回调中设置 httpOnly cookie 吗?或紧接着

if (res.ok && user) {
Run Code Online (Sandbox Code Playgroud)

就在返回用户之前?

use*_*311 7

我找到了一种只更新回调的方法:

  callbacks: {
    async jwt(token, user, account, profile, isNewUser) {
      if (user?.token) {
        token.token = user.token;
      }
      return token;
    },

    async session(session, token) {
      return session;
    }
  }
Run Code Online (Sandbox Code Playgroud)

这样,来自 API 的令牌现在存储在名为 httpOnly 的 cookie 中__Secure-next-auth.session-token(假设来自 API 的令牌采用上述格式)。