NextAuth会话未设置access_token

tcomlyy6  于 2023-05-17  发布在  其他
关注(0)|答案(2)|浏览(180)

如果我尝试给予用户一个access_token,它不会工作。我在session回调函数中得到的所有结果是:姓名、电子邮件、图像。但我需要其他信息,包括access_token

export const authOptions: NextAuthOptions = {
adapter: MongoDBAdapter(clientPromise),

providers:[
    GoogleProvider({
        clientId: process.env.GOOGLE_CLIENT_ID!!,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET!!,
       
      })
],
callbacks: {
    async jwt({ token, account, user }) {   
     if(account)
      {
     token.accessToken = account?.access_token 
      }      
     return token
    }, 
    async session({ session, token, user }) {
      //Gives me undefined
      console.log(token)
      if (token) {
      //No access_token from jwt
      session.user = token       
      }   

      console.log(session)
      return session
     
  },
  }
}

在客户端输出会话时的结果:

{
 user: {
 name: 'Max Mustermann',
 email: 'm.mustermann@test.com',
 image: 'https://lh3.googleusercontent.com/a/cweawwqad...=s96-c'       
},
 expires: '2023-06-11T14:23:17.361Z'
}
mkh04yzy

mkh04yzy1#

下一步Auth实际上分配了一个访问令牌,但出于安全原因,它没有将其与会话回调一起返回,但您可以保护路由而无需尝试,它将工作
如何在客户端中保护或获取会话:

//Session
import { useSession, signOut } from "next-auth/react"

const {data:session} = useSession()

    {!section?.user && (
    <div>
        <button>Login</button> 
    </div>
    )}

如何在API路由中保护或获取会话:

//auth 
import { getServerSession } from 'next-auth';
//the authOptions path 
import { authOptions } from '../api/auth/[...nextauth]'

export default async function handler(req, res) {
const { method } = req;

const session = await getServerSession(req, res, authOptions)

if(!session){
  return  res.status(401).send({ message: 'Not Authenticated!' }); 
}

}
如何在getServerSideProps中保护或获取会话:

//auth
import { getServerSession } from "next-auth/next"
//the authOptions path form api/auth/[...nextauth].js
import { authOptions } from '../../pages/api/auth/[...nextauth]';

export async function getServerSideProps(context) {

const session = await getServerSession(context.req, context.res, authOptions)

if (!session) {
  return {
    redirect: {
      destination: '/login',
      permanent: false,
    },
  }
}

const userData = session

return {
    props: {userData}
}

}

现在,如果你想在会话回调中添加一些东西,你可以在[...nextauth].js文件中这样做:

export const authOptions = {
  providers: [
    // OAuth authentication providers...
    GoogleProvider({
      clientId: process.env.GOOGLE_ID,
      clientSecret: process.env.GOOGLE_SECRET,
      authorization: {
        params: {
          prompt: "consent",
          access_type: "offline",
          response_type: "code"
        }
      }
    })
  ],
  callbacks:{
    //i use the sign in call back here to store the register user in my database
    signIn: async ({ user, account }) => {
      await dbConnect()

      if (account.provider === "google") {
        const existingUser = await User.findOne({ email: user.email });

        if (existingUser) {
          user.userData = existingUser 
          return existingUser;
        }
        
        const randomPassword = crypto.randomBytes(8).toString('hex');

        const hashedPassword = await hash(randomPassword, 12);

        const newUser = await User.create({
          name: user.name,
          email:user.email,
          password:hashedPassword,
          provider:true,
          providerName:"google",
          verified:true
        });

        //this will take the new user and put in the user object into userData
        user.userData = newUser 

        return newUser;
      }
    },
    jwt: async ({ token, user }) =>{

      if (user) {
        token.uid = user;
      }

      return token
    },
    session: async ({ session, token }) => {

        //here i created new object inside the session that hold the data that i want 
        session.userData = {
          isAdmin: token.uid.userData.isAdmin,
          id: token.uid.userData._id,
          image:token.uid.userData.image,
          provider:token.uid.userData.provider
        }

      //you have to return the session
      return session;
    },
  },
  strategy: "jwt",
  secret: process.env.NEXT_AUTH_SECRET,
  database: process.env.DB_URL  
}

export default NextAuth(authOptions)
pdsfdshx

pdsfdshx2#

这是我的答案,来自nextauth doc:
使用数据库会话时,User(用户)对象作为参数传递。
当使用JSON Web令牌进行会话时,将提供JWT有效负载(令牌)。
由于我使用MongoDB作为适配器,所以我没有返回access_token

相关问题