如何设置req.headers.authorization

时间:2014-06-02 18:01:08

标签: node.js

当我遇到以下几行时,我正在浏览nodejs中的一些身份验证代码并通过其他程序员编写解析

if (req.header.authorization) {
 // do soemthing 
} else {
var cookieValues = req.cookies["demo"]
}

令我困惑的是,在这段代码中没有任何地方我看到任何设置" header.authorization" req对象或响应对象的属性。

我在这里错过了什么?

2 个答案:

答案 0 :(得分:4)

Authorization是一个请求标头,通常用于HTTP Basic Auth。如果服务器请求授权,则设置它,然后浏览器提示用户输入用户名/密码并将其(base64编码)发送到服务器并发出后续请求。例如:

服务器发送:

WWW-Authenticate: Basic realm="your server"

客户发送:

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

另请参阅:http://en.wikipedia.org/wiki/Basic_access_authentication

答案 1 :(得分:3)

这是一个例子:

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);
});