Node.js

[node.js] HTTPS & Digest

behonestar 2016. 5. 4. 11:13

빨강 : HTTPS 관련 설정 

파랑 : Digest 관련 설정


index.js

var https = require('https')

  , fs = require('fs')

  , express = require('express')

  , bodyParser = require('body-parser')

  , passport = require('passport')

  , httpauth = require('./modules/httpauth')

  , path = require('path');


var options = {

key: fs.readFileSync(path.resolve(__dirname, 'ssl/key.pem')),

cert: fs.readFileSync(path.resolve(__dirname, 'ssl/cert.pem'))

};


var app = express();  

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: false }));

app.use(passport.initialize());

app.use(httpauth.authenticate, function(req, res, next){

  console.log('auth pass');

  next();

});


app.get('/', function (req, res) {

  console.log('/');

  res.sendStatus(200);

});


https.createServer(options, app).listen(8082, function(){

  console.log("Https server listening on port " + 8082);

});


modules/httpauth.js

var passport = require('passport')

  , DigestStrategy = require('passport-http').DigestStrategy

  

function pad(number, length) {

    var str = '' + number;

    while (str.length < length) str = '0' + str;

    return str;

}


function auth(userid, callback) {

  var password_db = userid + '1234'; // stored password in DB

  return callback(null, {userid:userid, password:password_db})

}


/*

The Digest strategy utilizes two callbacks, the second of which is optional.


The first callback, known as the "secret callback" accepts the username and calls done supplying a user and the corresponding secret password. The password is used to compute a hash, and authentication fails if it does not match that contained in the request.


The second "validate callback" accepts nonce related params, which can be checked to avoid replay attacks.

*/


passport.use(new DigestStrategy({ qop: 'auth' },

  function(userid, done) {

    auth(userid, function(err, user) {

      if (err) { return done(err); }

      if (!user) { return done(null, false); }

      return done(null, user, user.password);

    });

  },

  function(params, done) {

      return done(null, true);

  }

));


exports.authenticate = passport.authenticate('digest', { session : false });