Passport-koa2 is Koa-compatible authentication middleware for Node.js.
This package is not an official Passport package
It was developed willingly only for his compatibility with koa framework
$ npm install --save passport-koa2
The local authentication strategy authenticates users using a username and
password. The strategy requires a verify
callback, which accepts these
credentials and calls done
providing a user.
const passport = require('passport-koa2);
const 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); }
if (!user.verifyPassword(password)) { return done(null, false); }
return done(null, user);
});
}
));
Use passport.authenticate()
, specifying the 'local'
strategy, to
authenticate requests. It searches for fields in the query string and
ctx.body
, so ensure body parsers are in place if these fields are
sent in the body.
For example, as route middleware in an Koa application:
app.post('/login', passport.authenticate('local', { failureRedirect: '/login' }));
Callback:
app.post('/login', passport.authenticate('local', (err, result, ctx) => {
//
}));
There are 480+ strategies. Find the ones you want at: passportjs.org