这与我之前的问题有关。上下文是,我创建了一个
NextJS
应用程序,它使用 NextAuth
和 OneLogin
进行身份验证,使用 Mongo Atlas
进行数据库。顺便说一句,会话存储在数据库中。并主办于Vercel
。
问题是,MongoDB 连接数大多数时候都会超出限制,因为 Vercel 会单独考虑每个 HTTP 请求,因此无法缓存连接。因此,我计划将 API 部分分离到一个单独的 NodeJS+Express+MongoDB 应用程序中,单独托管。因此,数据库通信将通过要创建的 NodeJS API 应用程序进行,以便可以缓存连接。而且 Vercel 中托管的 NextJS 应用程序不会直接与数据库通信。
卡住的地方是,我将如何处理身份验证部分。由于我目前在 NextJS 应用程序中使用 NextAuth,而 OneLogin 是正在使用的提供程序,并且会话直接存储在数据库中,因此在我的新
NodeJS+Express API
应用程序中实现身份验证时感到困惑。
顺便说一句,我也计划稍后编写一个移动应用程序(
ReactNative
)。因此,将身份验证部分分离到 API 应用程序似乎是更好的选择。
因此,最初的问题表明您必须使用从 NextAuth 到会话/用户存储的无状态链接。有多种选择,但如果您要使用在其他地方托管的单独 Express 应用程序来处理身份验证和用户管理,则您的选择将减少为 http(s) 协议。
基本上,您需要在 NextAuth 端实现一个自定义适配器,并在 Express 端实现相应的 API。
例如适配器端的伪代码:
async getSessionAndUser(sessionToken) {
const response = await fetch(
`${EXPRESS_BASE_URL}/currentUser`,
{headers:{Authorisation: sessionToken}}
);
const data = response.json();
return {
user: from<AdapterUser>(data.user),
session: from<AdapterSession>(data.session),
}
}
在快递方面:
app.use(session); // passport, or any other auth middleware
app.get('/currentUser', function(req, res, next) {
const session = await db.sessions.findOne({ id: req.session.id });
const user = await db.users.findOne({ id: session.userId });
// or get user and session directly from the session
// if the auth middleware populates it with sufficient data
// required on NextAuth side
res.json({user, session})
})
正如我在评论中提到的,您可以使用 Atlas data-api 而不是 Express 应用程序。 NextAuth 适配器将使用相同的 http 传输来连接到 atlas,而不是 Express。
您可能必须创建一个连接池。 我们从 mysql 包中获得了这个。
var pool = mysql.createPool({
connectionLimit : 10, // this is the max number of connections that will be open at any given time from your application to sql db
host: '',
user: '',
database: '',
password: ""
});