1.0.3 • Published 5 months ago

passport-approved-token v1.0.3

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

Passport Approved Token Strategy

Approved token authentication strategy for Passport.

Installation

npm install passport-approved-token

Usage

The approved token authentication strategy authenticates users with a unique token. The strategy requires a verify callback, which accepts these credentials and calls done providing a user.

const passportApprovedToken = require('passport-approved-token');

passportApprovedToken(passport, () => {
    passport.use(
        new jwtStrategy(opts, (jwtPayload, done) => {
          console.log(jwtPayload);
          User.findById(jwtPayload.id)
            .then((user) => {
              if (user) {
                return done(null, user);
              }
              return done(null, false);
            })
            .catch((err) => console.log(err));
        })
      );
  });

By default passport-approved-token checks for token key credentials in either the params url or request body in these locations:

TypeDefault property
Urltoken
Bodytoken
Querytoken
Headertoken

How to Authenticate

Use passport.authenticate(), specifying the token strategy to authenticate requests.

For example, as route middleware in an Express application:

app.put('/animals/dogs', passport.authenticate('token'), (req, res) => {
  // User authenticated and can be found in req.user
});

If authentication fails in the above example then a 401 response will be given. However there may be times you wish a bit more control and delegate the failure to your application:

app.put('/animals/dogs', authenticate, (req, res) => {
  // User authenticated and can be found in req.user
});

function authenticate(req, res, next) {
  passport.authenticate('token', (err, user, info) => {
    if (err) {
      return next(err);
    }

    if (!user) {
      res.status(401).json({ message: 'Incorrect token credentials' });
    }

    req.user = user;
    next();
  })(req, res, next);
}

Credits

Mathias Derek

1.0.3

5 months ago

1.0.2

5 months ago

1.0.1

5 months ago