使用node.js进行Http授权

时间:2017-04-11 09:23:34

标签: javascript node.js http

我以前的server.js就像: 运行服务器后,我可以看到我的index.html

var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(5000, '192.168.xx.xx', function(){
    console.log('Server running on 5000');
});

我想创建http登录名和密码来保护网站,所以我在网上找到了http模块的信息:如果我输入正确的登录名和密码,我可以看到祝贺信息:

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 authorization</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 == 'admin') && (password == 'admin')) {   // Is the username/password correct?

                        res.statusCode = 200;  // OK
                        res.end('<html><body>Congratulations, feel free to explre!</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/"); });

我是nodejs的新手,我想知道如何结合这两个j?为了实现我向我的网站添加授权的功能。 我可以做一些事情来显示我的索引而不是在输入登录名和密码后显示祝贺消息吗?

非常感谢。

1 个答案:

答案 0 :(得分:1)

为了显示HTML页面而不是祝贺消息,您可以按照以下步骤操作:

  1. req.url获取请求路径,例如//introduction.html
  2. 根据上述路径,使用fs.readFile()
  3. 读取服务器磁盘中的相应HTML文件
  4. 如果读取成功,则将HTML文件内容返回给浏览器。否则,请返回404错误页面。
  5. 以上是上述步骤的一些示例代码:

    if((username == 'admin') && (password == 'admin')) {   // Is the username/password correct?
    
      res.statusCode = 200;  // OK
      // res.end('<html><body>Congratulations, feel free to explre!</body></html>');
      var requestURL = req.url; // e.g. / or /a or /a.html
      var requestFilePath = getFilePathFromRequestURL(requestURL); // you need to implement this logic yourself, such as "/" mapping to "./index.html"
      fs.readFile(requestFilePath, function(error, data) {
        if (error) {
          res.statusCode = 404;
          res.write('File not found.');
        } else {
          res.statusCode = 200;
          res.write(data);
        }
        res.end();
      });
    }
    

    但是,除非你想编写一些低级的node.js代码来更好地理解这种语言,否则我强烈建议使用node.js这样的Web框架,比如Express。使用低级node.js提供HTTP请求将是乏味的,尤其是在生产代码中。

    此外,请注意,使用WWW-Authenticate Basic进行身份验证既不安全也不方便用户使用。您需要一些其他方法来实现身份验证,例如JSON Web Tokens