Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs or ExpressJS Windows Authentication

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.

like image 709
lostpacket Avatar asked Apr 16 '13 14:04

lostpacket


1 Answers

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();
    }
}
like image 178
mrplatina Avatar answered Oct 07 '22 18:10

mrplatina