Node.JS 中的基本 HTTP 身份验证? [英] Basic HTTP authentication in Node.JS?

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

问题描述

我正在尝试使用 NodeJS 编写一个 REST-API 服务器,就像 Joyent 所使用的那样,以及一切没问题,只是我无法验证普通用户的身份验证.如果我跳转到终端并执行 curl -u username:password localhost:8000 -X GET,则无法在 NodeJS http 服务器上获取 username:password 值.如果我的 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
');
}).listen(1337, "127.0.0.1");

,我不应该在来自回调的 req 对象中的某处获取值 username:password 吗?如何在不必使用 Connect 的基本 http 身份验证 的情况下获取这些值?>

, shouldn't I get the values username:password somewhere in the req object that comes from the callback ? How can I get those values without having to use Connect's basic http auth ?

推荐答案

username:password 包含在 Authorization 标头中作为 base64 编码的字符串.

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

试试这个:

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

来自 HTTP 身份验证:基本和摘要式访问身份验证 - 第 2 部分基本身份验证方案(第 4 页-5)

Backus-Naur 形式的基本身份验证

basic-credentials = base64-user-pass
base64-user-pass  = <base64 [4] encoding of user-pass,
                    except not limited to 76 char/line>
user-pass   = userid ":" password
userid      = *<TEXT excluding ":">
password    = *TEXT

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

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