Unique token authentication strategy for Passport.
npm install passport-unique-token
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:
Type | Default property |
---|---|
Url | token |
Body | token |
Query | token |
Header | token |
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.
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);
}
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
)
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'
}));