Wednesday, 6 May 2015

basic authentication in express nodejs

Basic Authentication In Express Nodejs

To set a basic authentication to your project in node js. you need to have below modules.

npm install express --save
npm install basic-auth --save

Now use this module in your application

server.js

var express = require('express');
var auth = require('basic-auth');
var app = express();


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

    var user = auth(req);
    if (user === undefined) {
        res.statusCode = 401;
        res.setHeader('WWW-Authenticate', 'Basic realm="et3ebs6126a"');
        res.end('Unauthorized');
     } else
     {
        obj = new Object();
        obj.name = user['name'];
        obj.passkey = user['pass'];
                   console.log("Check Login");
            if(obj.name=="USERNAME" and obj.passkey="PASSWORD")
            {
                next();
            } else
            {
                res.statusCode = 401;
                res.setHeader('WWW-Authenticate', 'Basic realm="et3ebs6126a"');
                res.end('Unauthorized');
           }
    }
   
});



When ever you will try to open your project it will ask for authentication.

basic-auth-with-express-nodejs