Search code examples
passport.jsbasic-authenticationkoa

koa, passport-http strategy: basic authentication not working


I can't figure out how to make koa work with basic authentication. I have no problem with local strategy. So I thought I could implement basic auth easily. My home page is a form which post to /login route.

This is auth.js:

'use strict';

let passport = require('koa-passport'),
    co = require('co'),
    monk = require('monk'),
    wrap = require('co-monk'),
    db = monk('localhost/test'),
    users = wrap(db.get('users'));

function *getUser(username, password) {
  let user = yield users.findOne({username: username, password: password});
  return user;
};

passport.serializeUser(function(user, done) {
  done(null, user._id)
})

passport.deserializeUser(function(id, done) {
  done(null, id)
})

let BasicStrategy = require('passport-http').BasicStrategy
passport.use(new BasicStrategy(function(username, password, done) {
  co(function *(next) {
    try {
      return yield getUser(username, password);
    } catch (ex) {
      console.log('error: ', ex);
      return null;
    }
  }).then(function(user) {
    done(null, user);
  });
}));

This is server.js:

/* jshint node: true */

'use strict';

let koa = require('koa');

let app = koa();

// sessions
let session = require('koa-generic-session');
app.keys = ['your-session-secret'];
app.use(session());

// body parser
let bodyParser = require('koa-bodyparser');
app.use(bodyParser());

// authentication
require('./auth');
let passport = require('koa-passport');
app.use(passport.initialize()); 
app.use(passport.session());

// append view renderer
let views = require('koa-render');
app.use(views('./views', {
  map: { html: 'handlebars' },
  cache: false
}))

// public routes
let router = require('koa-router');

let pub = new router();

pub.get('/', function*() {
  this.body = yield this.render('login');
})

pub.post('/login',
  passport.authenticate('basic', {
    session: false
  }) 
)

pub.get('/logout', function*(next) {
  this.logout();
  this.redirect('/');
})

app.use(pub.routes());
app.use(pub.allowedMethods());


app.use(function*(next) {
  if (this.isAuthenticated()) {
    yield next
  } else {
      this.redirect('/')
    }
})

var secured = new router()

secured.get('/app', function*(next) {
  this.body = yield this.render('app');
})


app.use(secured.routes());
app.use(secured.allowedMethods());

app.listen(3000);

Using node 4.2.3 and these are the packages version I'm using:

"dependencies": {
"co": "^4.6.0",
"co-monk": "^1.0.0",
"handlebars": "^4.0.5",
"koa": "^1.1.2",
"koa-bodyparser": "^2.0.1",
"koa-generic-session": "^1.10.1",
"koa-passport": "^1.2.0",
"koa-render": "^0.2.1",
"koa-router": "^5.3.0",
"monk": "^1.0.1",
"passport-http": "^0.3.0"
}

After I compile the form and post my valid login form I recieve:

Request URL:http://localhost:3000/app
Request Method:GET
Status Code:302 Found
Remote Address:[::1]:300

This is just a sample I know password should be hashed, but I was just trying to get it working. Any ideas will be greatly appreciated. Thanks in advance


Solution

  • I found a solution. It was even fairly simple. Posting it here for everyone else who might be interested.

    Just comment:

    // app.use(function*(next) {
    //   if (this.isAuthenticated()) {
    //     yield next
    //   } else {
    //     this.redirect('/')
    //   }
    // });
    

    and change the secured route to:

    secured.get('/app', passport.authenticate('basic', {
      session: false}), function*(next) {
      this.body = yield this.render('app');
    });
    

    This way the auth middleware gets invoked whenever you try to access the protected route.