madhums / node-express-mongoose-demo

A simple demo app using node and mongodb for beginners (with docker)

Home Page:https://nodejs-express-demo.fly.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

This demo is great, but what about using JWT authentication?

sunkant opened this issue · comments

commented

This demo is great and help us a lot.

As now JWT ( JSON Web Token ) becomes an important way of authentication. What bout adding JWT authentication to this demo? Or we use JWT authentication instead of traditional session-cookie way.

Let's make this demo more powerful. : )

I believe it is generally accepted to mount a middleware function in front of your routes that require authentication and and perform your decoding within it.

commented

Hi @gvance,
Thanks, and I plan to do this. I plan to store the JWT in the cookie, and decode the JWT with a global JWT verifying middleware.

In this case, I find I do not need app.use(passport.session()); anymore, for I now record the User information in the JWT ( which is manually stored in the cookie by my application ).

With this global JWT verifying middleware, I also reduce the times the application need to access the Database, for we do not need to serializeUser and deserializeUser ( Load User by _id from the Database) everytime a req comes in. We just need to decode the JWT in the cookie, without visiting the Database.

Is this the right thing to do if I want to use JWT authentication? Thank you.

@Lucas-Qi
I would think of jwt as a different entity than a cookie. The nice thing about jwts is that they don't need to be a cookie but can still be passed to your API via a request header.

In this case, I find I do not need app.use(passport.session()); anymore, for I now record the User information in the JWT ( which is manually stored in the cookie by my application ).

This is correct.

We just need to decode the JWT in the cookie, without visiting the Database.

This is correct but upon validating the token I personally like to retrieve the validated user's document and use that for the life of the request (appending it to the request object itself), I believe you can apply that logic when you construct your passport strategy. The reason I retrieve an instance of the user and not just use the fields of the jwt is because it can be used to provide an extra layer of validation, ensuring that the user exists and if you have any other authorization checks (eg: admin or not, active or not, etc) you can easily perform them if you have access to the user.

commented

Hi @gvance,
Very clear and thank you! Thank you for sharing! Retrieving from database can indeed let us have more information about the user.

commented

So did anyone added JWT Authentication?

@parialegend Just working on it at the moment. I'm also adding user account verification.