Q:

How does req.headers.authorization get set

I was browsing through some authentication code in nodejs and restify written by a fellow programmer when I came across the following lines
if (req.header.authorization) {
 // do soemthing 
} else {
var cookieValues = req.cookies["demo"]
}

What got me confused is that nowhere in this code did I see any line that is setting the "header.authorization" property of the req object or response object. 
what am I missing here ? 

A:

Authorization is a request header, commonly use for HTTP Basic Auth.   It would be set if the server requested authorization, and the browser then prompted the user for a username/password and sent it (base64-encoded) to the server with a subsequent request.   For example:
Server sends:
WWW-Authenticate: Basic realm="your server"

Client sends:
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

See also:  http://en.wikipedia.org/wiki/Basic_access_authentication

A:

here is a example:
var express = require('express');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');

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

var app = express();

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

app.use(cookieParser('12345-67890-09876-54321')); // secret key

function auth( req, res, next){
    if (! req.signedCookies.user){//如果user不存在
    console.log(req.headers);
    var authHeader = req.headers.authorization;//获取认证情况的集合
    if(!authHeader){
        var err = new Error("you could not be authorized");
        err.status = 401;
        next(err);
        return;
    }
    console.log('authHeader :'+authHeader);
//cookie 里名称，密码形式为： user: password
    var auth = new Buffer(authHeader.split(' ')[1], 'base64').toString().split(':');
    var user = auth[0];
    var pass = auth[1];
    if (user == 'admin' && pass =='password') {
        res.cookie('user', 'admin', {signed: true});

        next();
    }else{
        var err = new Error("you could not be authorized");
        err.status = 401;
        next(err);

    }
}
    else {
        if (req.signedCookies.user == 'admin') {
            next();
        }else{
        var err = new Error("you could not be authorized");
        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);
});

// print
app.listen(port, hostname, function(){
    console.log('Server running at :'+hostname+ ': '+port);
});

