【问题标题】:next auth not passing all user info to the client下一个身份验证没有将所有用户信息传递给客户端
【发布时间】:2023-02-09 07:45:32
【问题描述】:

我正在尝试在会话中为用户扮演角色

这是我从客户端的 session.user 得到的

{ “电子邮件”:“测试值” }

我想得到什么

{ "email": "测试值", “角色”:“用户” }

出于某种原因,我可以访问服务器端的角色,但不能访问客户端

[...nextauth].ts

...
const authOptions: NextAuthOptions = {
  session: {
    strategy: "jwt",
  },
  providers: [
    CredentialsProvider({
      type: "credentials",
      credentials: {},
      async authorize(credentials, req) {
        const { email, password } = credentials as {
          email: string;
          password: string;
        };
        const saltRounds = 10;

        const db = path.join(process.cwd(), "db");

        const users = JSON.parse(fs.readFileSync(db + "/users.json", "utf-8"));

        type User = {
          id: string;
          email: string;
          name: string;
          role: "user" | "admin";
          password: string;
        };

        for (let i = 0; i < users.length; i++) {
          const e = users[i] as User;

          const emailMatch = e.email === email;

          if (emailMatch) {
            const passwordMatch = bcrypt.compareSync(password, e.password);

            if (passwordMatch) {
              console.log("user loggedin", e);

              return {
                id: e.id,
                email: e.email,
                name: e.name,
                role: e.role,
              };
            }
          }
        }

        throw new Error("Invalid email or password");
      },
    }),
  ],
  pages: {
    signIn: "/auth/signin",
  },
  callbacks: {
    jwt(params) {
      if (params.user?.role) {
        params.token.role = params.user.role;
      }
      console.log("jwt", params);
      return params.token;
    },
  },
};

export default NextAuth(authOptions);

我已经尝试搜索如何做到这一点,但我看不出我的代码有什么问题

【问题讨论】:

    标签: next.js next-auth


    【解决方案1】:

    这里你没有设置session,你必须使用会话回调从返回的token更新session

    async jwt(params) {
      if (params.user?.role) {
        params.token.role = params.user.role;
      }
      if (params.user?.email) {
        params.token.email = params.user.email;
      }
      return params.token;
    },
    async session({ session, token }) {
      session.role = token.role;
      session.email = token.email;
      return session;
    },
    

    【讨论】:

      猜你喜欢
      • 2020-09-24
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      • 2010-10-16
      • 2014-08-03
      • 2012-09-22
      • 1970-01-01
      相关资源
      最近更新 更多