1

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?

SSH This
  • 1,864
  • 4
  • 23
  • 41
  • You can create your own custom strategy – Sumeet Kumar Yadav May 19 '16 at 16:37
  • Yes, thx @Sumeet it sounds like perhaps there is not a strategy to address this. This question has some useful info: http://stackoverflow.com/questions/17397052/nodejs-passport-authentication-token but that suggests using "Local Strategy" to authenticate initially, then manually generating a token, and finally using passport-http-bearer Strategy to check the tokens. – SSH This May 19 '16 at 16:45

2 Answers2

1

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.

Community
  • 1
  • 1
nem035
  • 34,790
  • 6
  • 87
  • 99
-1

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

  1. generate token on login
  2. 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

Ujjwal
  • 378
  • 3
  • 5