Created
August 16, 2018 04:12
-
-
Save sampathsris/a79938cdf83141cf420971763e69595d to your computer and use it in GitHub Desktop.
Windows integrated authentication with Passport.js in pure JavaScript (without using IISNode or mod_auth_sspi).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const session = require('express-session'); | |
const passport = require('passport'); | |
const ntlm = require('express-ntlm'); | |
const ActiveDirectory = require('activedirectory'); | |
const CustomStrategy = require('passport-custom'); | |
const PORT = process.env.PORT || 8080; | |
const adconfig = { | |
url: process.env.AD_URL, | |
baseDN: process.env.AD_BASE_DN, | |
username: process.env.AD_USERNAME, | |
password: process.env.AD_PASSWORD | |
}; | |
// ugly hack to work with self-signed certificates in dev environment. | |
// DO NOT USE IN PRODUCTION! | |
process.env['NODE_TLS_REJECT_UNAUTHORIZED'] = 0; | |
const app = express(); | |
const AD = new ActiveDirectory(adconfig); | |
// Middleware to handl NTLM handshake | |
app.use(ntlm()); | |
app.use(session({ | |
// REPLACE THIS WITH A SECURE RANDOM NUMBER IN PRODUCTION! | |
secret: 'to be replaced with a more secure random number', | |
resave: true, | |
saveUninitialized: true | |
})); | |
app.use(passport.initialize()); | |
app.use(passport.session()); | |
passport.serializeUser((user, done) => { | |
done(null, user); | |
}); | |
passport.deserializeUser((id, done) => { | |
done(null, id); | |
}); | |
passport.use('ntlm-ad-backend', new CustomStrategy((req, done) => { | |
let username = req.ntlm.UserName; | |
AD.findUser(username, (err, profile) => { | |
if (err) { | |
console.log(err); | |
done(err); | |
} | |
if (!profile) { | |
done(new Error(`User ${req.ntlm.UserName} not found in Active Director.`)); | |
} else { | |
done(null, profile); | |
} | |
}); | |
})); | |
// Middleware to ensure user is logged in | |
const isLoggedIn = (req, res, next) => | |
req.isAuthenticated() ? next() : res.redirect('/auth'); | |
app.get('/', isLoggedIn, (req, res) => { | |
let { displayName, mail } = req.user; | |
res.end(`You are logged in as ${displayName} (${mail}).`); | |
}); | |
app.get('/unsecured', (req, res) => { | |
res.end('You are not logged in.'); | |
}); | |
app.get('/auth', passport.authenticate('ntlm-ad-backend', { | |
successRedirect: '/', | |
failureRedirect: '/unsecured' | |
})); | |
app.listen(PORT); | |
console.log('Listening on port ' + PORT); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
At line 25, the usage ntlm() will not verify credentials with AD. You may not want to do this if there is no other web server (IIS, Apache httpd) doing NTLM verification.