简体   繁体   中英

NextAuth + OneLogin in NodeJS + Express API

This is related to my previous question . The context is, I have created a NextJS app, which uses NextAuth with OneLogin for authentication and Mongo Atlas for database. Session is stored in db btw. And is hosted in Vercel .

The problem is, MongoDB connections exceeds the limit most of the times as Vercel considers each HTTP requests separately and thus caching of the connections is not possible. So am planning to separate the API part to a separate NodeJS+Express+MongoDB application, hosted separately. So the db communication will take place through this NodeJS API app that am gonna create, so that the connections could be cached. And the NextJS app hosted in Vercel won't directly communicate with the db.

Place where am stuck is, how would I take care of the authentication part. Since am using NextAuth at the moment for the NextJS app, and OneLogin is the provider that am using and sessions are stored directly in database, confused at implementing the authentication in my new NodeJS+Express API app.

Btw, I plan to code a mobile app( ReactNative ) later too. So separating the authentication part to the API app seems to be the better option.

So the original problem dictates that you have to use a stateless link from NextAuth to the session/user storage. There are several options, but if you are going to use a separate Express app hosted elsewhere to handle authentication and user management, your options are reduced to http(s) protocol.

Basically you need to implement a custom adapter on NextAuth side, with corresponding API on the Express side.

eg pseudocode on the adapter side:

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),
    }
}

and on express side:

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})
})

As I mentioned in the comment, you can use Atlas data-api instead of Express app. NextAuth adapter will use the same http transport to connect to atlas instead of Express.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM