我正在开发一个类似于Zappier的集成工具。我想使用Next-auth连接到一个或多个应用程序,并保存它们的访问令牌。然而,Next-auth一次只允许一个会话。如何使用Next-auth同时存储多个会话?
export const authOptions = {
// Configure one or more authentication providers
secret: 'tsfsdf',
providers: [
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
authorization: {
params: {
scope: 'openid https://www.googleapis.com/auth/gmail.compose https://www.googleapis.com/auth/gmail.modify'
}
}
}),
{
clientId: process.env.QUICK_BOOKS_CLIENT_ID,
clientSecret: process.env.QUICK_BOOKS_CLIENT_SECRET,
id: 'quickbooks',
name: 'QuickBooks',
type: 'oauth',
wellKnown: 'https://developer.api.intuit.com/.well-known/openid_sandbox_configuration',
authorization: { params: { scope: 'com.intuit.quickbooks.accounting openid profile email phone address' } },
idToken: true,
checks: ['pkce', 'state'],
profile(profile) {
console.log(profile, 'profile')
return {
id: profile.sub,
name: profile.name,
email: profile.email,
image: profile.picture
}
}
}
// ...add more providers here
],
callbacks: {
async session({ session, token, user }) {
session.user.id = token.id
session.accessToken = token.accessToken
return session
},
async jwt({ token, user, account, profile, isNewUser }) {
if (user) {
token.id = user.id
}
if (account) {
token.accessToken = account.access_token
}
return token
}
}
}发布于 2022-12-01 12:57:01
为此,您可以简单地向authOptions对象中的提供者数组中添加更多的对象。每个提供程序对象都应该有自己的配置,例如clientId、clientSecret和授权参数。
当用户使用提供程序进行身份验证时,将使用包含该提供程序访问令牌的令牌对象调用回调对象中的会话回调函数。您可以使用此访问令牌代表用户发出API请求。
要同时保存多个会话,可以将访问令牌保存在数据库中,也可以保存在Redis这样的会话存储系统中。然后,当用户使用新的提供程序进行身份验证时,可以检索现有会话并将新的访问令牌添加到会话列表中。
下面是一个如何使用数据库实现此操作的示例:
// In the session callback function
async session({ session, token, user }) {
// Check if the user already has any sessions stored in the database
const existingSessions = await db.getUserSessions(user.id);
// Add the new access token to the list of sessions
existingSessions.push({ provider: token.provider, accessToken: token.accessToken });
// Save the updated list of sessions to the database
await db.saveUserSessions(user.id, existingSessions);
return session;
}这只是如何使用Next-auth实现多个会话的一个例子。也可能有其他方法来实现这一点。
https://stackoverflow.com/questions/74641723
复制相似问题