Search code examples
node.jsexpresspassport.jsexpress-jwt

JWT with Node & Passport: Restarting server


I am new to Node and trying to setup Node & Passport to create JWTs upon authentication.

I am hoping to build a "stateless authentication mechanism" to reduce the need of going back and forward to the database.

By going "stateless", if none of the shared secrets or JWT is saved in the DB, I am assuming if the server restarts, all the issued JWTs (logged in users) are invalidated, thereby requiring a new JWT for all users to access protected routes. I do not want the users to log back in each time a server restarts or a new instance is spun.

I believe I can pass in static shared secret(s) to Node environment that I can use each time to generate the same JWTs that doesn't affect server restart.

Questions:

  1. If a good practice is to pass in the shared secrets, where and how should I create this shared secret? and what all shared secret(s) will I have to pass in?

  2. However, if passing in shared secret(s) to Node environment is not a good strategy, I am all ears for suggestions?

Update

I meant shared secrets when I said "key(s)". I'll update the question so it's not confusing.


Solution

  • Actually passing the keys as environment is the recommended way for this kind of applications.

    Because the environment is only be visible by the running application and reduces the possibilities of leaking the keys (compared to something like a config file provided with the rest of the application code).

    Normally you don't rotate the keys that often, it's usual to rotate them once a month assuming that you control your environment.

    But keep in mind that the key is only used to prove that the token was signed by you, normally is good practice to only include a tiny bit of information in the token (for performance reasons). So you still need to go to the database to retrieve extra information about the user itself. You can add all the user information inside the token but keep in mind that the token needs to be sent for each request and that adds overhead.

    If you use a process manager like supervisord you can set the environments over there and give the appropriate permissions to the config file to avoid key leakage.

    I normally use environments to pass that kind of information to my node applications, I use it for JWT, AWS keys, SMTP credentials, etc. It keeps your code decoupled and avoids possible mistakes like pushing private keys to public code versioning system like github.