Basic HTTP authentication in Node.JS?

后端 未结 7 1776
遇见更好的自我
遇见更好的自我 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:13

    The username:password is contained in the Authorization header as a base64-encoded string.

    Try this:

    http.createServer(function(req,res){
      var header=req.headers['authorization']||'',        // get the header
          token=header.split(/\s+/).pop()||'',            // and the encoded auth token
          auth=Buffer.from(token, 'base64').toString(),    // convert from base64
          parts=auth.split(/:/),                          // split on colon
          username=parts[0],
          password=parts[1];
    
      res.writeHead(200,{'Content-Type':'text/plain'});
      res.end('username is "'+username+'" and password is "'+password+'"');
    
    }).listen(1337,'127.0.0.1');
    

    Detail on http authorization can be found at http://www.ietf.org/rfc/rfc2617.txt

提交回复
热议问题