json - NextAuth中如何使用JWT存储数据
问题描述
确认凭据后,我返回以下 JSON:
{username: 'foo', name: 'bar', type: 123}
但是,由于模型限制,NextAuth 不允许我存储所有字段,所以它在 JWT 中返回给客户端的是:
{name: 'bar', email: null, image: null}
我的[...nextauth].js设置非常基本:
providers: [
Providers.Credentials({
async authorize(credentials) {
const res = await fetch('http://localhost:3000/api/user', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'credentials': JSON.stringify(credentials)
}
})
const user = await res.json()
if (user && !user.message) {
return user
} else {
return null
}
}
})
],
我想出的唯一解决方案是使用 JSON 字符串伪造电子邮件字段,我可以在其中存储我需要的所有内容:
{name: 'bar', email: "{username: 'foo', type: 123}", image: null}
我怎样才能正确地做到这一点?我尝试研究自定义模型(https://next-auth.js.org/tutorials/typeorm-custom-models),但它似乎只是关于数据库,这不是我的情况,因为我使用 JWT 进行会话存储。如果我继续我的解决方案,我还会遇到什么缺点?
解决方案
You will need to persist the additional info through callbacks, at first through JWT's callback and then Session's callback:
callbacks: {
async jwt(token, user, account, profile, isNewUser) {
// Since you are using Credentials' provider, the data you're persisting
// _should_ reside in the user here (as far as can I see, since I've just tested it out).
// This gets called whenever a JSON Web Token is created (once) or updated
if (user?.type) {
token.status = user.type
}
if (user?.username) {
token.username = user.username;
}
return token
},
async session(session, token) {
session.type = token.type;
session.username = token.username;
return session
}
}
推荐阅读
- javascript - 计时器未在 React 组件内运行
- sublimetext3 - 如何在 Linux 上的 sublime 中为命令添加助记符
- nest-api - 在设备访问控制台上访问和编辑 Pub/Sub 主题
- sql - 查找一行是否以 clob 中的指定字符串开头,然后提取
- javascript - 如何获取表格的所有行并将其显示在警报消息中?
- python - Python api 发布请求
- javascript - 正则表达式捕获位填充
- typescript - 找不到模块“C:\native\win32\x64\12.13.0\edge_nativeclr”
- javascript - 当 playlist.m3u8 文件不断更新时,如何播放 HLS 流?
- python-3.x - 根据行值和行值总和为零在熊猫中创建新列