Title: How to minimize the number of database calls needed to authenticate a user?
Tags: node.js;express;session;socket.io;express-session
Question: I need to authenticate users trying to connect to my server.

My first architecture queried the database three times in order to identify any given user:


first ```express-session``` checked for a valid session associated with
the session ID given by the user
then again ```passport.js``` queried the
database to deserialize the user and check for special privileges
```socket.io``` needed to associate new sockets with a user ID (no additional data needed), thus checking again for a valid session


My first intuition was to scrap ```passport.js``` and to write a custom ```express-session``` store to merge the first two steps into one single call to the database.

But now I am left wondering if there is any way to reuse that same call to identify sockets as well, thus potentially offering several benefits (reduced database traffic, single authentication logic etc).

One idea I had:
switch entirely to JSON web tokens to store the user ID along with an expiry date client-side. Sockets can then be identified without even querying the database (by signing JWTs). User deserialization only takes one database call.

Is it a secure and viable option?

Potential drawbacks I am concerned about off the top of my head:


no session management: I don't see any way to selectively log someone
off (as opposed to simply ```DELETE```ing the row in the session table
associated with a specific user ID)
how to ensure that there is at most one socket associated with a connected user?
ill-intentioned individuals simply need a copy of the encrypted web token to hijack someone's session
it would still require some form of interaction with the database e.g. to check if a user is banned


Is there any other efficient way to authenticate a user across multiple channels?

Comment: As for ***ill-intentioned individuals simply need a copy of the encrypted web token to hijack someone's session***, that is generally the case with any browser session management (whether it uses a cookie, a custom header or a URL query parameter).  You need to run under https to make it less likely someone can grab the session credential.



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2019:00:11/16/19', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<node.js><express><session><socket.io><express-session>', 'Title': 'How to minimize the number of database calls needed to authenticate a user?', 'ViewCount': 73, 'id': 58886466, 'user_AboutMe': '', 'user_AccountId': 7142532.0, 'user_DisplayName': 'Kathandrax', 'user_Reputation': 844.0, 'user_Views': 62.0, 'user_id': 5459567.0}}