NextAuth、NextJS - getToken 在中间件函数中始终返回 null

Ngu*_*ịnh 6 middleware jwt next.js next-auth

环境


  • NextJS:12.2.2
  • NextAuth:4.10.3(最新)
    • 提供者:凭证
  • 浏览器:谷歌浏览器
  • 节点:LTS

问题


大家好

我使用 NextAuth 通过凭证提供程序和策略 jwt 进行身份验证,但函数 getToken 在我的中间件中始终返回 null,而 NextAuthOptions 中的 jwt 回调不返回 null

我检查了cookie存储中的令牌并尝试解码令牌,结果解码仍然正确

变量环境 NEXTAUTH_SECRET 已添加到文件 .env.local 中

代码


src/page/api/auth/[...nextauth].ts

export const decode = async (data: any) => {
  const { secret, token } = data;
  const verify = jwt.verify(token, secret) as JWT;
  return verify;
};
export const encode = async (data: any) => {
  const { secret, token } = data;

  const payload = {
    username: token.username,
    email: token.email,
    _id: token._id,
  };
  const accessToken = jwt.sign(payload, secret, {
    expiresIn: '1209600s',
    algorithm: 'HS512',
  });
  return accessToken;
};

export const authOptions: NextAuthOptions = {
  providers: [
    CredentialsProvider({
      type: 'credentials',
      credentials: {},
      async authorize(credentials: any, req) {
        const { username, password } = credentials as {
          username: string;
          password: string;
        };

        try {
          const { data } = await client.mutate({
            mutation: login,
            variables: {
              userInput: {
                username,
                password,
              },
            },
          });

          const { user } = data.login;

          const response = {
            username: user.username,
            email: user.email,
            _id: user._id,
          };
          return response;
        } catch (error) {
          throw new Error('Unauthorized');
        }
      },
    }),
  ],
  session: {
    strategy: 'jwt',
    maxAge: 60 * 60 * 24 * 14,
  },
  jwt: {
    maxAge: 60 * 60 * 24 * 14,
    secret: process.env.SECRET,
    encode: encode,
    decode: decode,
  },
  pages: {
    signIn: '/auth/login',
    signOut: '/logout',
    error: '/auth/login',
    newUser: '/auth/register',
    verifyRequest: '/auth/verify',
  },
  callbacks: {
    async signIn({ user }) {
      return user ? true : false;
    },
    async session({ session, token }) {
      session.username = token.username;
      session.email = token.email;
      session._id = token._id;
      session.user!.name = token.username as string;
      session.user!.email = token.email as string;
      return session;
    },
    async jwt({ token, user }) {
      if (user?.username) {
        token.username = user.username;
        token.email = user.email;
        token._id = user._id;
      }

      return token;
    },
  },
};
export default NextAuth(authOptions);
Run Code Online (Sandbox Code Playgroud)

src/中间件.ts

export default withAuth(function middleware(req: NextRequest) {}, {
  callbacks: {
    authorized: function ({ token }) {
      console.log(token); // token is always null

      return true;
    },
  },
});

export const config = { matcher: ['/chat', '/notifications'] };
Run Code Online (Sandbox Code Playgroud)

m_w*_*wer 4

嘿,有同样的问题,更新到这里next@12.2.5提到的,修复了它。

  • 整个讨论对我来说毫无用处,我正在使用 Next 13.1.2,这个问题仍然是一场噩梦 (2认同)