Passportjs handle guest authentification for HTTP API

Here is my code:

passport = require 'passport'
BasicStrategy = require('passport-http').BasicStrategy

passport.use new BasicStrategy((username, pwd, done) ->
  console.log arguments
  if pwd is "1234" and username is "Foo"
    done undefined, {
      username: "Foo"
      role: "admin"
    }
  else done()
)


express = require("express")
app = express()

app.use express.logger()
app.use passport.initialize()
app.use passport.authenticate("basic", session: false)

app.get '/', (req, res) -> res.send req.user

But with this way it works only when the user is authentificated using a header. When no authorization header is specified, I just get 401 on '/'. Is there a way to make authentification optional? Or a restful way to specify an authorization to say "Hi, I'm a guest"?

The passport-http middleware will call fail() if Authorization header is missing.

You could write your own authentication strategy, or fork and modify passport-http, or add a middleware that will add the header if missing, ie.

GUEST = "Basic #{new Buffer('guest:guest').toString('base64')}"
app.use (req, res, next) ->
  req.headers['authorization'] = GUEST unless req.headers['authorization']
  next()

You'll need to add this middleware before you call app.use(passport...). Then in the strategy you could do eg.

passport.use new BasicStrategy (user, pass, done) ->
  if user == pass == 'guest'
    done null, {username: 'Guest'}
  else
    ...