Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/40.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ajax 在处理POST请求时,查明谁已在节点上使用basicAuth进行身份验证_Ajax_Node.js_Rest_Authentication - Fatal编程技术网

Ajax 在处理POST请求时,查明谁已在节点上使用basicAuth进行身份验证

Ajax 在处理POST请求时,查明谁已在节点上使用basicAuth进行身份验证,ajax,node.js,rest,authentication,Ajax,Node.js,Rest,Authentication,我使用basicAuth对特定地址上的帖子进行身份验证 在客户端,我使用以下形式的命令: $.ajax({ type: "POST", accepts: "text/plain", url: "http://localhost:3000/somewhere", data: JSON.stringify(something), contentType: "application/json; charset=UTF-8"

我使用basicAuth对特定地址上的帖子进行身份验证

在客户端,我使用以下形式的命令:

$.ajax({
        type: "POST",
        accepts: "text/plain",
        url: "http://localhost:3000/somewhere",
        data: JSON.stringify(something),
        contentType: "application/json; charset=UTF-8", 
        dataType: "json",
        success: function(data) {
            window.alert("Received back: '" + data + "'");
        },
        username: theUsername,
        password: "a password"
    });

从存储在username中的用户名通过我在节点上的身份验证机制的意义上讲,这很好。当用户通过身份验证时,我可以打印一条console.log语句,看看谁真正通过了身份验证(我现在不验证密码)。但是,POST请求的实际处理将开始。但是,在这一点上,我如何才能计算出原始请求中使用的用户名和密码?我试图查看请求的标题,但没有看到任何内容。

当您收到基本身份验证请求时,您应该能够在
req.headers.authorization中读取“authorization”标题。authorization
您必须取出base64编码的凭据,然后对其进行解码。大概,在Express中,您使用
req.header(“授权”)
req.get(“授权”)

作为一个独立的示例,请看一下我在下面复制的内容,以供将来参考

var http = require('http');

var server = http.createServer(function(req, res) {
        // console.log(req);   // debug dump the request

        // If they pass in a basic auth credential it'll be in a header called "Authorization" (note NodeJS lowercases the names of headers in its request object)

        var auth = req.headers['authorization'];  // auth is in base64(username:password)  so we need to decode the base64
        console.log("Authorization Header is: ", auth);

        if(!auth) {     // No Authorization header was passed in so it's the first time the browser hit us

                // Sending a 401 will require authentication, we need to send the 'WWW-Authenticate' to tell them the sort of authentication to use
                // Basic auth is quite literally the easiest and least secure, it simply gives back  base64( username + ":" + password ) from the browser
                res.statusCode = 401;
                res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');

                res.end('<html><body>Need some creds son</body></html>');
        }

        else if(auth) {    // The Authorization was passed in so now we validate it

                var tmp = auth.split(' ');   // Split on a space, the original auth looks like  "Basic Y2hhcmxlczoxMjM0NQ==" and we need the 2nd part

                var buf = new Buffer(tmp[1], 'base64'); // create a buffer and tell it the data coming in is base64
                var plain_auth = buf.toString();        // read it back out as a string

                console.log("Decoded Authorization ", plain_auth);

                // At this point plain_auth = "username:password"

                var creds = plain_auth.split(':');      // split on a ':'
                var username = creds[0];
                var password = creds[1];

                if((username == 'hack') && (password == 'thegibson')) {   // Is the username/password correct?

                        res.statusCode = 200;  // OK
                        res.end('<html><body>Congratulations you just hax0rd teh Gibson!</body></html>');
                }
                else {
                        res.statusCode = 401; // Force them to retry authentication
                        res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');

                        // res.statusCode = 403;   // or alternatively just reject them altogether with a 403 Forbidden

                        res.end('<html><body>You shall not pass</body></html>');
                }
        }
});


server.listen(5000, function() { console.log("Server Listening on http://localhost:5000/"); });
var http=require('http');
var server=http.createServer(函数(req,res){
//console.log(req);//调试转储请求
//如果他们传入一个基本的auth凭证,它将位于一个名为“Authorization”的头中(注意NodeJS将其请求对象中头的名称小写)
var auth=req.headers['authorization'];//auth在base64中(用户名:password),因此我们需要解码base64
log(“授权头是:”,auth);
如果(!auth){//没有传入授权头,那么这是浏览器第一次访问我们
//发送401需要身份验证,我们需要发送“WWW Authenticate”来告诉他们要使用哪种身份验证
//基本身份验证实际上是最简单和最不安全的,它只是从浏览器返回base64(用户名+“:”+密码)
res.statusCode=401;
res.setHeader('WWW-Authenticate','Basic realm=“Secure Area”');
res.end(“需要一些信任儿子”);
}
否则,如果(auth){//传递了授权,那么现在我们验证它
var tmp=auth.split(“”);//在空间上拆分,原始的auth看起来像“Basic y2hhcmxlczoxmj0nq==”,我们需要第二部分
var buf=newbuffer(tmp[1],'base64');//创建一个缓冲区,并告诉它传入的数据是base64
var plain_auth=buf.toString();//将其作为字符串读回
日志(“解码授权”,普通授权);
//此时,请使用plain_auth=“用户名:密码”
var creds=plain_auth.split(“:”);//在“:”上拆分
var username=creds[0];
var password=creds[1];
如果((用户名='hack')&&(密码='thegibson')){//用户名/密码正确吗?
res.statusCode=200;//确定
res.end(‘恭喜你刚刚得到吉布森!’);
}
否则{
res.statusCode=401;//强制他们重试身份验证
res.setHeader('WWW-Authenticate','Basic realm=“Secure Area”');
//res.statusCode=403;//或者干脆以403禁止的名称将它们全部拒绝
res.end(“你不能通过”);
}
}
});
监听(5000,function(){console.log(“服务器正在监听http://localhost:5000/"); });

我在以下意义上绕过了这个问题。在文档()中,它提到了req.user将用于记录用户。但是,它实际上写下了授权函数的返回值。因此,当某人未经授权时,我将返回false,否则我将返回用户名。然后,通过req.user,我可以访问授权的用户名。很明显,我可以返回一个包含用户名和密码的结构,并同时获取它们。无论如何,谢谢你抽出时间。由于你的努力,我接受了。谢谢,我认为这个答案可能对其他可能发现这个问题的人有所帮助。供将来参考,节点!==快递:)。是的,使用Express可以将完整的用户凭据作为对象返回,这将成为req.user的值