New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

passport-unique-token

Package Overview
Dependencies
Maintainers
1
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

passport-unique-token

Unique Token authentication strategy for Passport.

  • 3.0.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Maintainers
1
Created
Source

Passport Unique Token Strategy

CircleCI Maintainability Test Coverage Codacy Badge npm npm GitHub Conventional Commits Known Vulnerabilities

Unique token authentication strategy for Passport.

Installation

npm install passport-unique-token

Usage

The unique 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 { UniqueTokenStrategy } = require('passport-unique-token');

passport.use(
  new UniqueTokenStrategy((token, done) => {
    User.findOne(
      {
        uniqueToken: token,
        expireToken: { $gt: Date.now() },
      },
      (err, user) => {
        if (err) {
          return done(err);
        }

        if (!user) {
          return done(null, false);
        }

        return done(null, user);
      },
    );
  }),
);

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

TypeDefault property
Urltoken
Bodytoken
Querytoken
Headertoken

Configure

These credential locations can be configured when defining the strategy as follows:

const { UniqueTokenStrategy } = require('passport-unique-token');
const strategyOptions = {
  tokenQuery: 'custom-token',
  tokenParams: 'custom-token',
  tokenField: 'custom-token',
  tokenHeader: 'custom-token',
  failOnMissing: false
};

passport.use(new UniqueTokenStrategy(strategyOptions,
  (token, done) => {
    User.findOne({
      uniqueToken: token,
      expireToken: { $gt: Date.now() }
    }, (err, user) => {
      if (err) {
        return done(err);
      }

      if (!user) {
        return done(null, false);
      }

      return done(null, user);
    });
  }

failOnMissing option allows you to queue multiple strategy, customizing the behavior. By default it's set to true, when it's set to false it lets move on to the next strategy on failure.

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);
}

Api Reference

UniqueTokenStrategy()

The token authentication strategy authenticates requests based on the credentials submitted through standard request headers, body, querystring or params.

new UniqueTokenStrategy(
  options?: {
    // the token field name in the body request
    tokenField?: string = 'token',
    // the token field name in the query string request
    tokenQuery?: string = 'token',
    // the token field name in the param request
    tokenParams?: string = 'token',
    // the token field name in the header request
    tokenHeader?: string = 'token',
    // if `true` the express.Request is the first parameter of the verify callback
    passReqToCallback?: false,
    // if `true` the token key is case sensitive (e.g. res.body['uniqueToken'])
    caseSensitive?: false,
    // allows you to queue multiple strategy, customizing the behavior.
    failOnMissing?: true
  },
  verify: (
    req?: express.Request,
    token: string,
    done: (err: Error | null, user?: any, info?: any) => void
  ) => void
)

authenticate()

You can optionally pass options to the authenticate() method. Please refer to the passport documentation for the different signature.

authenticate(
  strategyName: string,
  options?: { badRequestMessage: string },
  callback?: { err: Error, user: any, info: any }
);

// Example:

app.post('/login', passport.authenticate('token', {
  badRequestMessage: 'custom error message'
}));

Credits

Luca Pau

Keywords

FAQs

Package last updated on 09 Jul 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc