【问题标题】:How do I receive the user id from a session using next-auth?如何使用 next-auth 从会话中接收用户 ID?
【发布时间】:2023-02-11 05:21:03
【问题描述】:

我已经阅读了session callbacks 上的文档,并尝试通过保留 JWT 令牌来实现它,但仍然无法正常工作。文档还说,当将 NextAuth 与数据库(在我的例子中是 Firebase,请参阅适配器)一起使用时,它应该:

将 NextAuth.js 与数据库一起使用时,用户对象将是数据库中的用户对象(包括用户 ID)(如果用户之前已登录)或用户的更简单的原型用户对象(即姓名、电子邮件、图像)以前没有登录过的人。

在没有数据库的情况下使用 NextAuth.js 时,用户对象将始终是原型用户对象,并从配置文件中提取信息。

我在这里错过了什么?

[...nextauth].ts

import { FirestoreAdapter } from "@next-auth/firebase-adapter";
import NextAuth from "next-auth";
import GithubProvider from "next-auth/providers/github";
import GoogleProvider from "next-auth/providers/google";

export const authOptions = {
  // Configure one or more authentication providers
  providers: [
    GithubProvider({
      clientId: process.env.GITHUB_ID as string,
      clientSecret: process.env.GITHUB_SECRET as string,
    }),
    GoogleProvider({
      clientId: process.env.GOOGLE_ID as string,
      clientSecret: process.env.GOOGLE_SECRET as string,
    }),
  ],
  adapter: FirestoreAdapter({
    apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
    appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
    authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
    databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
    projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
    storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  }),
  callbacks: {
    async jwt({ token, account, profile }: any) {
      // Persist the OAuth access_token and or the user id to the token right after signin
      if (account) {
        console.log("token", token);
        token.accessToken = account.access_token;
        token.id = profile.id;
      }
      return token;
    },
    async session({ session, token, user }: any) {
      // Send properties to the client, like an access_token and user id from a provider.
      if (token) {
        session.accessToken = token.accessToken;
        session.user = {};
        session.user.id = token.id;
      }
      return session;
    },
  },
};

export default NextAuth(authOptions);

控制台记录会话给我:

【问题讨论】:

    标签: next.js next-auth


    【解决方案1】:

    你的代码看起来不错,我正在做下一个项目,我的代码几乎一样,唯一的区别是我使用的是CredentialsProvider

    session.accessToken = token.accessToken;
    session.user = {};
    ession.user.id = token.id;
    

    应该覆盖会话,它对我有用。

    问题应该出在 if(token) 语句中,这个语句以某种方式返回 false 尝试 console.log 里面看看

    【讨论】:

    • 这很奇怪;我已经记录了用户并且确实有一个 ID。但是当我尝试在会话中记录令牌时,没有。这是正常的吗?我现在确实解决了我的问题,返回if (user) { session.user = {}; session.user.id = user.id;}
    • 是的,我确定没有令牌
    • 你明白这是为什么吗?
    • 我不知道可能是因为在使用数据库时无法从会话回调访问令牌对象。
    猜你喜欢
    • 2022-01-21
    • 2023-02-06
    • 2022-01-21
    • 1970-01-01
    • 2022-12-25
    • 2021-08-17
    • 2021-12-04
    • 2022-12-04
    • 2022-12-11
    相关资源
    最近更新 更多