我尝试添加自定义数据到session.user,但它不工作。奇怪的是,如果我发送这个:
const user = { id: '1', name: "J Smith", email: "jsmith@example.com", };
然后我使用useSession在我的page.jsx上接收该信息,并在控制台中打印它:
const { data: session } = useSession(); console.log("in form session: ", session);
但问题是当我尝试向用户添加自定义信息时:
const user = { userId: res.data.data.login.userId, companyId: res.data.data.login.companyId, };
它打印空用户对象,没有自定义信息,只有当我使用id,name和email时才有效。
这是我的完整代码:
import NextAuth from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import axios from "axios";
const handler = NextAuth({
providers: [
CredentialsProvider({
name: "Credentials",
credentials: {
email: {
label: "Email",
type: "email",
placeholder: "Enter your email",
},
password: { label: "Password", type: "password" },
},
async authorize(credentials, req) {
const res = await axios({
method: "POST",
url: `${process.env.NEXT_PUBLIC_AUTH_URL}/api`,
data: {
query: `
query Login($email: String!, $password: String!) {
login(email: $email, password: $password) {
userId
token
tokenExpiration
companyId
}
}
`,
variables: {
email: credentials.email,
password: credentials.password,
},
},
});
// Validation
if (res.data.errors) {
throw new Error(res.data.errors[0].message);
}
const user = {
userId: res.data.data.login.userId,
companyId: res.data.data.login.companyId,
};
if (user) {
return user;
}
// // Return null if user data could not be retrieved
return null;
},
}),
],
session: {
strategy: "jwt",
},
pages: {
signIn: "/login",
signOut: "/logout",
},
secret: process.env.NEXTAUTH_SECRET,
});
export { handler as GET, handler as POST };
有人知道怎么修吗?谢谢
1条答案
按热度按时间ss2ws0br1#
检查jwt回调,它将从Credentials提供者接收用户,以及会话回调,它将在客户端中公开您需要的数据(例如useSession)
我已经解决了这个问题,我把我的答案贴在这里,也许它能帮助将来的人。我错过了jwt和会话回调和会话回调。因为默认情况下,出于安全原因,next-auth不会暴露所有内容。
添加此修复它:
并且回调将向客户端公开访问令牌。