Basic HTTP authentication in Node.JS?

后端 未结 7 1805
遇见更好的自我
遇见更好的自我 2020-11-28 21:09

I\'m trying to write a REST-API server with NodeJS like the one used by Joyent, and everything is ok except I can\'t verify a normal user\'s authentication. If I jump to a t

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 21:10

    It can be implemented easily in pure node.js with no dependency, this is my version which is based on this answer for express.js but simplified so you can see the basic idea easily:

    var http = require('http');
    
    http.createServer(function (req, res) {
        var userpass = new Buffer((req.headers.authorization || '').split(' ')[1] || '', 'base64').toString();
        if (userpass !== 'username:password') {
            res.writeHead(401, { 'WWW-Authenticate': 'Basic realm="nope"' });
            res.end('HTTP Error 401 Unauthorized: Access is denied');
            return;
        }
        res.end('You are in! Yay!');
    }).listen(1337, '127.0.0.1');
    

提交回复
热议问题