Passport JWT & Authorize vs Authenticate - passport.js

Passport seems like a great option for simple authentication, unobtrusive and not hard to setup. I'm building a MEAN stack that authenticates using JWT so I looked to Passport JWT. However there's a few things I'm confused about.
1) Am I correct in assuming that Passport JWT is only used for authenticating requests, not for generating a valid jwt? That is, should it only be used for validating the presence of a token?
2) What's the difference between passport.authorize and passport.authenticate? And when should I use one over the other?
3) I have 3 routes I'm using for authentication related matters, login, signup, and authenticate.
login will check if the user email/password combo exists and matches and then generate a token for the client.
signup will check to make sure the email doesn't already exist and then generate a token for the client.
Now for authenticate this is where I get a little mixed up. Would I even need an authenticate route if I already have login and signup? If anything, it seems like authenticate would be the function that I pass into passport.use for the JWT strategy and then login and signup with the possible addition of a verify_token route would be my only unprotected routes, where everything else would have a call to passport.authenticate or passport.authorize.

Correct. Passport JWT (passport-jwt) is only for authenticating requests. You'll need another tool to actually generate a token. This tutorial uses JWT Simple (jwt-simple) and I've used jsonwebtoken (per this reference).
I haven't seen any references to passport.authorize, so I believe passport.authenticate is what you're looking for. passport.authenticate is what you'll use in your routes to verify that an incoming request has the JWT token and is allowed.
Since you're generating a token via both login and signup, authenticate is redundant and unnecessary. Just make sure you use passport.authenticate in your routes to verify access during requests.
The general setup steps to keep in mind here are:
passport-jwt is for authentication
you need another tool to create a JWT token
the JWT token, which you generate and return to whatever made the request, needs to be present in the header ("Authorization: JWT eyJ0eXAiO...") on subsequent requests
you need to setup your JWT strategy and tell passport to use it
use passport.authenticate to verify access via the JWT token in the header for incoming requests, like:
router.post('/users', passport.authenticate('jwt', {session: false}), function(req, res) {
// do something...
});

Related

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

Node JS Express secure route

I want to have some kind of auth to make protected routes.
For example, the GET /forecastweather should be protected. While the GET /generalweather should not.
I read the express 4.x documentation (https://expressjs.com/en/4x/api.html) but I can't find an authentication function. I also looked in the req (https://expressjs.com/en/4x/api.html#req) documentation to see if there is an attribute to request I can use.
If I'm right express had basic auth function, but it seems to be gone. What is the best way to protect routes by some kind of bearer token.
There is no "best" way to do authentication. There are just multiple different ways and you have to decide which fits your situation the best.
First, you need to decide how you're going to deliver your credential which likely depends upon what type of client you're using.
Token in a cookie (often works best for browser access)
Token in a custom header (often used for programmatic access for APIs)
Token in query parameter (not as common)
Once you decide how the token is going to be delivered, you then have to figure out how the client is going to get their token. This would typically be some sort of form submission that contains credentials (such as username and password) and the return from a successful verification of those credentials would be the token.
To process this form, you'd create a POST request handler in Express and verify the credentials, returning a token if the credentials are valid.
Then, within Express, you'd create a router that contains the authenticated routes and add some middleware to that router that verifies that a valid token is present on the request before allowing the request to proceed. This will protect all the routes on this router.

is passport required when using JWT

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.

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/

Trade username and password for a token

I have a Node.js application that offers several different routes in front of MongoDB. I need to make sure that only authenticated requests can access these routes.
Ideally, I want to set it up so that a username and password comes in to the API, and in a response we give them back a token. I don't mind managing the tokens inside MongoDB myself, but I need to make sure that the token we give back can make authenticated requests. I don't want to force the user to send their credentials each time, just the token.
I've read for a few days about passport, and there's currently 307 strategies. Which strategy am I describing here?
Which strategy am I describing here?
You are describing a Local Strategy.
As per their description:
This module lets you authenticate using a username and password in your Node.js applications.
I don't want to force the user to send their credentials each time, just the token.
Passport auth strategies just provide various ways to authenticate (or in simple terms login) the user, not how to persist that login. Login persistence is usually done with user sessions.
One way you can solve this is to combine the local strategy with the express session middleware. Combination of the two allows for a fairly simple auth system that requires the user to login once and then persists the session.
In a typical web application, the credentials used to authenticate a user will only be transmitted during the login request. If authentication succeeds, a session will be established and maintained via a cookie set in the user's browser.
Each subsequent request will not contain credentials, but rather the unique cookie that identifies the session. In order to support login sessions, Passport will serialize and deserialize user instances to and from the session.
PassportJS docs give an example how to achieve this.
For this you should prefer generating JWT tokens for a the login and then using the token to always authenticate user actions.
Following steps are need to implement this style of token login system
generate token on login
verify when token supplied and use the decoded data to identify user
use should proper middleware in order to protect your api.
Here is a link you could follow:
https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

Resources