is passport required when using JWT - node.js

Very basic question but probably I miss something very big in the big picture.
I cannot figure out whether passport.js is needed or not when using JWT auth. Most examples have it but I fail to see the need.
In my app, there is a /login route and once the user authenticates successfully ( local auth, I check user, a hash pair in the database) I create a token with user id in it, set an expiry, sign it and send it back as the cookie in the response. Then I check the req cookies, decrypt and if they contain user id and not expired, I consider the request authenticated. (also traffic is https only if it changes anything)
Am I doing something wrong here as I don't have passport etc. in the process?

No, JWT (RFC 7519) is a standard. passport.js is an implementation that uses JWT. It is not required.

Related

How can I secure my Node.js backend api data?

I may be a little confused about how backend servers work. Let's say I have a frontend React app with a login. The login information is stored in a database (i.e. MSSQL, MySQL, MongoDB) and I have a Node backend with routes for my app to fetch that information when a user is logging in or doing anything. When both my React app and server are hosted, I would make calls to the api and no confidential information (such as passwords) would be sent back to the client (just maybe a "success" message if the login information appears to be correct on the backend). My question is, what is stopping someone from finding the backend route and putting it into Insomnia to get the password or other sensitive information?
My first thought was to use express-session and auth on the backend to require a user to be logged in to an account to make such requests, but I think there are two issues with that:
How will that work when multiple users are logging in at once? Since the users are not technically physically visiting the api routes themselves, does session still know who is signing in to what account on the frontend? Will the second person logging in override the first person's session even though the first hasn't logged out yet?
If the auth doesn't kick in until a person is logged in, wouldn't someone be able to get the response password data from the login route itself?
Sorry if the question sounds dumb I'm just having a little trouble understanding the security aspect.
It sounds like there's a bit of a misunderstanding of how auth sessions work. There are two primary way sessions can work - either storing the sessions on the backend (older way), or storing session data in a cookie, typically a JWT (JSON Web Token). Cookies are bits of data that are passed from the server to the browser and anytime the browser makes a subsequent request to your server, it passes the cookie back too, so your server will always be able to get that data. The way this works for auth is the following:
A user signs into your application with credentials (username and password).
Your server validates the credentials by checking your database or wherever you're storing them and rejects the request if it fails. (Check out Auth0, Firebase Auth, or other auth services as doing this yourself can be a pain and open yourself up to potential vulnerabilities)
If the credentials are valid, the server generates a signed JWT token that includes data, like the username of the user.
The server responds with the body as well as a cookie containing the JWT, which the browser then stores.
The user requests some user-specific data from your server, and the browser sends the cookie with the JWT back to your server.
Your server validates that the JWT is valid by checking the signature. If it is valid, it uses the username from the token to get the user-specific data. If it is not valid, it rejects the request.
Because the signature occurs entirely on the server side (typically with some hashing algorithm and a secret key that you don't vend publicly), it would be nearly impossible for someone to spoof a JWT token signature. Therefor, your server is able to 1. trust that the JWT token is indeed valid if the signature is correct, and 2. find out what user is requesting data.
Here's a video that helps explain and visualize this: https://www.youtube.com/watch?v=soGRyl9ztjI
And here's a library for creating and validating JWTs in Node: https://www.npmjs.com/package/jsonwebtoken
Hopefully that answers your question!

passport google strategy with jwt

I did jwt authentication in my previous projects but never worked with oauth/passport auth before..
it's been 3 days i have been learning about passport strategies and i have implemented google+ strategy.
I got new project and this project requires to let users signup/signin themselves with google or facebook or with signup-form using firstName, lastName, phone number and password..
Very briefly in jwt server sends a token to the client and then client sends that particular token in the request header back to server to have access to protected routes.
In passport google strategy a cookie is saved in the browser and is send to server on each request.
What i think is
i cant use two different approaches in one project.. like if i use jwt for signup form and cookie for google strategy how am i gonna protect my routes then? with token in headers or with cookie in browser
Now my question is
how can i use both in the same project?
In google strategy should i generate jwt (token) for client in serializeUser() or somewhere else or what else is possible?
Or should i save jwt token in a browser cookie like passport?
I presented things very briefly, i hope you get it what i'm trying to do here
i cant use two different approaches in one project.. like if i use jwt for signup form and cookie for google strategy how am i gonna protect my routes then? with token in headers or with cookie in browser
You can. Cookie is just a transport mechanism for data between your browser and the server. You can store anything in it (up to allowed size limit) meaning that you can store JWT in a cookie (rather common practice especially for server side rendered single page apps).
You don't even have to develop a custom solution because this is already provided by passport in passport-jwt.
In the scenario where you require to signup the user using predefined fields you could use something known as Local Strategy which is present in passport.passport-local

Where can we store the JWT token securely?

1. User will do the login UserName and password.
2. If the login success then server will return JWT.
3. Now we will store the token.
4. Now for every request we will send the JWT Token for authentication on server.
My question is that Where can we store the JWT token because Local storage,Session,Cookies is not safe.
"Only the server should know the "secret" that is used to generate the JWT. If someone modifies the data contained in the JWT, the server will fail to decode it. So the server can trust any JWT that it can decode."
You don't need to store JWT token where someone can't find. And if you think if hackers get token of someone, there is a expiration date option for this.
Check this: How safe is JWT?
httpOnly cookie
It's a special kind of cookie that’s only sent in HTTP requests to the server, and it’s never accessible (both for reading or writing) from JavaScript running in the browser.
Check this:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
You can use this Package to make your life easier if you want:
https://www.npmjs.com/package/react-cookie

Why would I need to use passport package with jsonwebtoken for applying token based authentication on a NodeJs web API?

passport , passport-jwt , jsonwebtoken , express-jwt ..etc
I’m confused, when to use which and which to use with which?
I was building my own MEAN app not too long ago and ran into the same questions. This cleared it up very well.
https://jonathanmh.com/express-passport-json-web-token-jwt-authentication-beginners/
Basically, you use jsonwebtoken to generate the token. This is returned to the client who in turn sends it every time he makes a request. This is typically passed in the auth header. Passwort-jwt check this auth header and verifies it's validity. If it is invalid, it returns a 401, otherwise it populate your req.user.
passport-jwt:
In this strategy, server validates user credentials and returns encrypted user object i.e token. Client can save token using cookie, local-storage, or other mechanism. Then on every user request it validates token and proceed request.
express-jwt:
You can use it as multi-tenancy purpose like,
Validate user credentials and encrypt data like passport-jwt.
https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens
OAuth: you can create jwt token and validate using secret key.
https://auth0.com/learn/json-web-tokens/

Restful API Authentication and Session management for Express.js

I have been researching on RESTful authentication alot, and I still can't get a very clear idea, how can I design my web architecture. I have many questions that are unanswered.
I want my API to be served to mobile and web too and I am using Express v4.
I don't want to use Basic Authentication, as many posts have suggested as a simple way out, or I can use the Passport middleware, but I want to use token based authentication or something similar or better,and I want to make my authentication, so I could understand better, but I am not sure how can I achieve it.
I will simplify my intended authentication architecture below:
Registration of a new user
Client side
Post username and password to server
(I know if you want to make the connection secured is to use https connection, or else I will expose my credentials, or you got any other options besides https? or else I will need to use the public and private key with timestamp and hash my credentials before sending to server? How can i do this? Is there any other better option?
Server side
Hashed the password using salt cryptography, and stored the hashed password and salt, then generate a token ID and sent to the client, and the token ID is stored in sessions or using the REDIS database?
Isn't that using sessions violates REST again? But, if I don't use sessions, how can I store the token ID and compare it with the client side?
Client side
Since now I have the token ID, how can I store on client side?
Should I use cookie? If yes, will this violate the RESTful? And how can my mobile application store the cookie too?
What other options can I have besides cookie? I can't think of any.
Authorizing API
Client side
Now, I have the token ID, I will place this in the authorization header each time I would like to make a request to the server.
Server side
When a request is received, the server will check the token API, and compare it with the session token, if it is true, request allow else reject
Is this a standard way for Express application authorization?
I am sorry for the lengthy post, but I feel that I should really master the authentication and authorization because it is important. I do hope someone can correct my misconception of REST authentication and answer my questions or suggest me a better way to do it.
Send the user credentials encoded over https
To compare the token at the client side you can either keep it in map or in Redis store corresponding to user id and match it to consider user authenticated. It does not kills the significance of Rest as in Rest as well authorization tokens are sessions only which after expiry
Express does not have any specific or standard method of authorization , it only enables you to use any db in backend to perform authentication and authorization as required by your application
Your solution is the use JWT tokens for your authentication .You can read more about JWT at https://medium.com/dev-bits/a-guide-for-adding-jwt-token-based-authentication-to-your-single-page-nodejs-applications-c403f7cf04f4
With JWT tokens you can have a token base auth system with no sessions UID at cookies , but you have to implement logic to handle tokens that have sign out something like blacklist tokens.

Resources