Saturday, 22 April 2017

Basic Auth in NodeJs doesn't work

I created the following nodejs script,which has to do with basic authentication. I run the server by typing node server,so the local url is localhost:3000. In my browser,I should be getting a prompt window where I could put the username and password. Instead of it the prompt window doesn't appear and I get a message Welcome to express.

    var express = require('express');
    var morgan = require('morgan');

    var hostname = 'localhost';
    var port = 3000;

    var app = express();

    app.use(morgan('dev'));

    function auth (req, res, next) {
        console.log(req.headers);
        var authHeader = req.headers.authorization;
        if (!authHeader) {
            var err = new Error('You are not authenticated!');
            err.status = 401;
            next(err);
            return;
        }

        var auth = new Buffer(authHeader.split(' ')[1], 'base64').toString().split(':');
        var user = auth[0];
        var pass = auth[1];
        if (user == 'admin' && pass == 'password') {
            next(); // authorized
        } else {
            var err = new Error('You are not authenticated!');
            err.status = 401;
            next(err);
        }
    }

    app.use(auth);

    app.use(express.static(__dirname + '/public'));
    app.use(function(err,req,res,next) {
                res.writeHead(err.status || 500, {
                'WWW-Authenticate': 'Basic',
                'Content-Type': 'text/plain'
            });
            res.end(err.message);
    });

    app.listen(port, hostname, function(){
      console.log(`Server running at http://${hostname}:${port}/`);
    });

Any ideas why is this happening?

Thanks,

Theo.



via Theo

No comments:

Post a Comment