Last Updated: February 25, 2016
·
658
· pmaoui

HTTP Authentification with Express 3 / NodeJS

This protip is in CoffeeScript. If you want plain javascript, use http://js2coffee.org

Caution : HTTP authentification is not the best way to authenticate your user (due to its lack of disconnect feature), it can be sometime useful.

 We need a function to test the credential user. There are 3 ways to do that.

 The very simple one:

auth = express.basicAuth "bob", "password"

The synchronous one:

auth = express.basicAuth (user,pass)->
    if user is "bob" and pass is "pass"
        return true
    else
        return false

The asynchronous one:

auth = express.basicAuth (user,pass,callback)->
    if user is "bob" and pass is "pass"
        callback null,true
    else
        callback null,false

Enable the authentification

If you want global authentification:

app.use auth

 If you just want to protect a specific path :

app.get '/protectedPage',auth,(res,req)->
    console.log req.remoteUser + ' is asking that page'