next auth未将所有用户信息传递给客户端。

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

next auth not passing all user info to the client

问题

这是您要翻译的内容:

我正在尝试在会话中为用户设置一个角色

这是我从客户端的 `session.user` 中获取的内容
```js
{ "email": "test value" }

我想要获得的是:

{ 
  "email": "test value",
  "role": "user"
}

由于某种原因,我可以在服务器端访问角色,但在客户端无法访问

[...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 an 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);

我已经为您翻译了代码部分,不包括代码中的引号转义。如果您需要更多帮助或有其他问题,请随时提问。

英文:

I am trying to have a role for the user in the session

This is what I get from session.user on the client :

{ "email": "test value" }

what I want to get :

{ 
  "email": "test value",
  "role": "user"
}

For some reason I can access the role on the server side but not on the client

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

I have tried searching for how to do it and I dont see what's wrong with my code.

答案1

得分: 0

这里您没有设置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;
},

由于您已将属性role添加到token,所以在服务器端您可以访问role,但在客户端上不行,现在您必须将属性添加到您的session

英文:

Here you are not setting the session you have to use the session callback to update the session from the returned token:

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

>For some reason I can access the role on the server side but not on the client

that's the role from the token because you have added the property role to it now you have to add properties to your session

huangapple
  • 本文由 发表于 2023年2月9日 01:11:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75389333.html
匿名

发表评论

匿名网友

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

确定