如何为NextAuth V5的Google Provider添加自定义字段?
解决NextAuth V5中Google Provider自定义返回字段的问题
要在NextAuth V5的Google Provider中添加自定义字段(比如username),需要通过Provider的profile回调和全局的session回调配合实现,具体步骤如下:
1. 配置Google Provider的profile回调
在Google Provider的配置中添加profile函数,用于处理Google返回的用户信息,提取或生成自定义字段:
Google({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, // 自定义profile处理函数 profile(profile) { // 从Google返回的profile中提取字段,或生成自定义字段 return { id: profile.sub, name: profile.name, email: profile.email, image: profile.picture, // 示例:用邮箱前缀作为username username: profile.email.split('@')[0], // 可选:添加Google返回的其他原生字段 firstName: profile.given_name, lastName: profile.family_name, }; }, }),
注意:Google OAuth默认返回的用户信息中没有原生的
username字段,通常需要从邮箱前缀、用户姓名等现有字段生成,或后续让用户自行设置。如果需要获取Google的其他额外信息,需在authorization参数中添加对应Scope(比如https://www.googleapis.com/auth/userinfo.profile)。
2. 配置session回调传递自定义字段
默认情况下,NextAuth的Session不会包含自定义字段,需要在全局配置的callbacks.session中,将自定义字段添加到返回的Session对象中:
export default { providers: [ // Google、Github、Credentials配置... ], callbacks: { session({ session, user }) { if (session.user) { // 将自定义字段注入到session.user中 session.user.id = user.id; session.user.username = user.username; session.user.firstName = user.firstName; session.user.lastName = user.lastName; } return session; }, }, } satisfies NextAuthConfig;
完整修改后的代码
import Credentials from "next-auth/providers/credentials"; import bcrypt from "bcryptjs"; import { LoginSchema } from "@/schemas"; import type { NextAuthConfig } from "next-auth"; import { getUserbyEmail } from "@/data/user"; import Github from "next-auth/providers/github"; import Google from "next-auth/providers/google"; export default { providers: [ Google({ clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, profile(profile) { return { id: profile.sub, name: profile.name, email: profile.email, image: profile.picture, username: profile.email.split('@')[0], firstName: profile.given_name, lastName: profile.family_name, }; }, }), Github({ clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, }), Credentials({ async authorize(credentials) { const validdatedFields = LoginSchema.safeParse(credentials); if (validdatedFields.success) { const { email, password } = validdatedFields.data; const user = await getUserbyEmail(email); if (!user || !user.password) return null; const passwordsMatch = await bcrypt.compare(password, user.password); if (passwordsMatch) return user; } return null; }, }), ], callbacks: { session({ session, user }) { if (session.user) { session.user.id = user.id; session.user.username = user.username; session.user.firstName = user.firstName; session.user.lastName = user.lastName; } return session; }, }, } satisfies NextAuthConfig;
这样配置后,无论是在服务器端的session对象,还是客户端通过useSession获取的用户信息,都会包含自定义的username、firstName等字段。
内容的提问来源于stack exchange,提问作者Jean Mako
相关产品推荐
相关产品推荐

