NextAuth中如何使用JWT存储数据 [英] How to use JWT to store data in NextAuth

查看:22
本文介绍了NextAuth中如何使用JWT存储数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在确认凭据后返回以下 JSON:

I return the following JSON after confirming credentials:

{username: 'foo', name: 'bar', type: 123}

但是,由于模型限制,NextAuth 不允许我存储所有字段,所以它在 J​​WT 中返回给客户端的是:

However, NextAuth does not allow me to store all the fields due to model limitations, so what it returns in JWT to client is:

{name: 'bar', email: null, image: null}

我的 [...nextauth].js 设置非常基本:

My [...nextauth].js setup is very basic:

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 字符串伪造电子邮件字段,我可以在其中存储我需要的所有内容:

The only solution I came up with is to fake email field with JSON string in which I can store everything I need:

{name: 'bar', email: "{username: 'foo', type: 123}", image: null}

我怎样才能正确地做到这一点?我尝试研究自定义模型(https://next-auth.js.org/tutorials/typeorm-custom-models),但它似乎只与数据库有关,这不是我的情况,因为我使用 JWT 进行会话存储.如果我继续我的解决方案,我还会遇到什么缺点?

How can I do it properly? I tried looking into custom models (https://next-auth.js.org/tutorials/typeorm-custom-models), but it seems to be only about databases, which is not my case since I use JWT for session storage. Also what drawbacks I can encounter if I continue with my solution?

推荐答案

你需要通过回调持久化附加信息,首先通过 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
    }
  }

这篇关于NextAuth中如何使用JWT存储数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆