barndog
barndog

Reputation: 7163

Passport JWT & Authorize vs Authenticate

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.

Upvotes: 12

Views: 4006

Answers (1)

user3006381
user3006381

Reputation: 2855

  1. 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).
  2. 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.
  3. 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...
});

Upvotes: 11

Related Questions