Developer990 Developer990 - 2 months ago 17
Node.js Question

Token Authentication/Authorization With PassportJS

I'm currently in the process of developing a Node/Express-based API for an application that will be distributed on multiple platforms. Because of this, I will need to authenticate/authorize users based on a token rather than sessions/cookies.

After doing some research, I've found that PassportJS is a great plugin for accomplishing something like this. Unfortunately, after going through its documentation for several hours, there doesn't seem to be any good explanation of raw token-based authentication.

I don't want to use any plugins such as JWT -- just Passport, Express, and MongoDB.

How would I go about implementing a token-based user authorization system with Passport. I need explanations on token generation, token passing, and the rest of the process.

Please answer this in a clear and concise manner, as if you're explaining to a 5th grader.

Thanks :)

Answer

I'm going to try and break down your question into a few parts:

  • Configuring Passport
  • Where to use Passport
  • Miscellaneous final remarks

First, a slight misconception. Passport doesn't come bundled with a token generation system. Passport is designed to be configured with strategies that you have to include as dependencies. This is done so Passport itself can be light and modular. I might need to authenticate with Twitter when you need a local (username and password) authentication strategy. So, Passport includes neither. I install what I need and keep the package size light.

TL;DR: There's no way of not installing a plugin for Passport. You need to include a strategy of some kind.

I'm going to assume you want to use a local strategy. So, you need passport-local. Don't worry, it was written by Jared Hanson, the author of Passport.

Most everything I use will be from the Passport docs, specifically here.

Let's look at configuration:

  • Install Passport and the passport-local module.
  • Make sure Express, MongoDB, Node, npm, etc. are up to date.

The basic configuration file for passport-local looks like this:

var passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
    function(username, password, done) {
        User.findOne({ username: username ), function(err, user) {
            if (err) { return done(err); }
            if (!user) {
                return done(null, false, { message: 'Incorrect username.' });
            }
            if (!user.validPassword(password)) {
                return done(null, false, { message: 'Incorrect password.' });
            }
            return done(null, user);
        });
    }
));

Now you need to place a form on a web page. Here is a very basic example:

<form action="/login" method="post">
    <div>
        <label>Username:</label>
        <input type="text" name="username" />
    </div>
    <div>
        <label>Password:</label>
        <input type="password" name="password" />
    </div>
    <div>
         <input type="submit" value="Log In" />
    </div>
</form>

Next, you need a route in your Express app. See the Express Routing Documentation for more info on how this works.

app.post('/login',
    passport.authenticate('local', { successRedirect: '/',
                                     failureRedirect: '/login' })
);

Note on parameters: By default, LocalStrategy expects the credentials to be in parameters named username and password. There are configuration options to name them otherwise, for instance logging in with email rather than a username.

Comments