I am trying to authenticate openLDAP username and password using passport-ldapauth npm. While executing the below code I am always getting error as
{ message: 'Missing credentials' }
. Kindly help me what is wrong with my code.
var connect = require('connect'),
app = connect(),
passport = require('passport'),
LdapStrategy = require('passport-ldapauth');
// Credentials from the free LDAP test server by forumsys
// More info at: http://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/
var OPTS = {
server: {
url: 'ldap://<ip>',
bindDn: '<admin username>',
bindCredentials: '<admin password>',
usernameField: "<passing actual username>",
passwordField: "<password>"
}
};
passport.use(new LdapStrategy(OPTS));
app.use(passport.initialize());
app.use(connectRoute(function (router) {
router.post('/login', function (req, res, next) {
passport.authenticate('ldapauth', {session: false}, function (err, user, info) {
console.log(info);
if (err) {
return next(err); // will generate a 500 error
}
// Generate a JSON response reflecting authentication status
if (!user) {
return res.send({success: false, message: 'authentication failed'});
}
return res.send({success: true, message: 'authentication succeeded'});
})(req, res, next);
});
}))
app.listen(8080);
For more details, please see this badRequestMessage flash message for missing username/password (default: 'Missing credentials')
Here is my configuration:
var passport = require('passport');
var LdapStrategy = require('passport-ldapauth').Strategy;
var OPTS = {
server: {
url: '<ldap server>',
bindDn: '<admin username>',
bindCredentials: '<admin password>',
searchBase: '<base dn>',
searchFilter: '(sAMAccountName={{username}})'
}
};
passport.use(new LdapStrategy(OPTS));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
The usernameField
and passwordField
in OPTS
are optional. My program is using the default value username
and password
. If the usernameField
is set, you need to modify searchFilter
as (sAMAccountName={{<usernameField value>}})
or (uid={{<usernameField value>}})
.
Also, in order to store the login status in your session, express-session
module is required. The session configuration is like:
var session = require('express-session');
app.use(session({
secret: 'ldap secret',
resave: false,
saveUninitialized: true,
cookie : { httpOnly: true, maxAge: 2419200000 } /// maxAge in milliseconds
}));
Then, you can use the LDAP authentication as:
app.post('/login', passport.authenticate('ldapauth', {
successRedirect: '/users/profile', failureRedirect: '/login'
}));