在Node.js的基本HTTP验证? [英] Basic HTTP authentication in Node.JS?

查看:202
本文介绍了在Node.js的基本HTTP验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写与像 Joyent的所使用的一个的NodeJS REST的API服务器,一切都很好,除了我可以T检验一个普通用户的身份验证。如果我跳转到一个终端,做卷曲-u用户名:密码本地主机:8000 -X GET ,我不能让值用户名:对HTTP的NodeJS服务器密码。如果我的NodeJS HTTP服务器是一样的东西。

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 terminal and do curl -u username:password localhost:8000 -X GET, I can't get the values username:password on the NodeJS http server. If my NodeJS http server is something like

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
}).listen(1337, "127.0.0.1");

,我不应该得到的值用户名:密码某处的 REQ 对象来自回调?
我怎样才能获得这些值,而无需使用连接的基本HTTP认证

推荐答案

用户名:密码被包含在授权头的为Base64-CN codeD字符串

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

试试这个:

http.createServer(function(req,res){
  var header=req.headers['authorization']||'',        // get the header
      token=header.split(/\s+/).pop()||'',            // and the encoded auth token
      auth=new Buffer(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');

在HTTP授权详细信息可以在 http://www.ietf.org/rfc/rfc2617.txt

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

这篇关于在Node.js的基本HTTP验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆