I would like to authenticate a windows user in NodeJS
app.
Is there any add-on for this yet ? There is node-krb5
but it doesn't support windows yet.
If you host on IIS with iisnode https://github.com/auth0/passport-windowsauth works nicely! passport-windowsauth comes with an ad integration but if you only want the username in order to implement your own authorzation logic you can do it like this
web.config:
<system.webServer>
<iisnode promoteServerVars="LOGON_USER" />
</system.webServer>
server.js:
var passport = require('passport');
var WindowsStrategy = require('passport-windowsauth');
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use(new WindowsStrategy({
integrated: true
}, function(profile,done) {
var user = {
id: profile.id,
};
done(null, user);
}));
app.all("*", passport.authenticate("WindowsAuthentication"), function (request,response,next){
next();
});
then you can access the userid on the request object in your other routes:
app.get("/api/testAuthentication", function(request, response){
console.log(request.user.id + " is authenticated");
});
if you want to implement your own authorization logic using the user id you can define a middleware function like this:
app.get("/api/testAuthorization", hasRole("a role"), function(request, response, next){
console.log(request.user.id " is authenticated and authorized");
});
where hasRole looks like this:
function hasRole(role) {
return function(request,response,next){
//your own authorzation logic
if(role == "a role")
next();
else
response.status(403).send();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With