簡體   English   中英

Node.JS 中的基本 HTTP 身份驗證?

[英]Basic HTTP authentication in Node.JS?

我正在嘗試使用 NodeJS 編寫一個 REST-API 服務器,就像Joyent使用的那樣,除了我無法驗證普通用戶的身份驗證外,一切都很好。 如果我跳轉到終端並執行curl -u username:password localhost:8000 -X GET ,則無法在 NodeJS http 服務器上獲取 username:password 值。 如果我的 NodeJS http 服務器類似於

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對象中的某處獲取值 username:password 嗎? 如何在不必使用Connect 的基本 http auth 的情況下獲取這些值?

username:password作為 base64-encoded string包含在 Authorization 標頭

嘗試這個:

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

如果您使用 express,則可以使用 connect 插件(包含在 express 中):

//Load express
var express = require('express');

//User validation
var auth = express.basicAuth(function(user, pass) {     
   return (user == "super" && pass == "secret");
},'Super duper secret area');

//Password protected area
app.get('/admin', auth, routes.admin);

如果在您的路線圖中添加來自外部服務的授權,您可以將node-http-digest用於基本身份驗證或everyauth

我將此代碼用於我自己的帶有 auth 的入門網站。

它做了幾件事:

  • 基本認證
  • 為 / 路由返回 index.html
  • 在不崩潰的情況下提供內容並靜默處理錯誤
  • 運行時允許端口參數
  • 最少的日志記錄

使用代碼前,npm install express

var express = require("express");
var app = express();

//User validation
var auth = express.basicAuth(function(user, pass) {     
     return (user == "username" && pass == "password") ? true : false;
},'dev area');

/* serves main page */
app.get("/", auth, function(req, res) {
try{
    res.sendfile('index.html')
}catch(e){}
});

/* add your other paths here */

/* serves all the static files */
app.get(/^(.+)$/, auth, function(req, res){ 
try{
    console.log('static file request : ' + req.params);
    res.sendfile( __dirname + req.params[0]); 
}catch(e){}
});

var port = process.env.PORT || 8080;
app.listen(port, function() {
    console.log("Listening on " + port);
});

restify 框架 (http://mcavage.github.com/node-restify/) 包括用於“基本”和“簽名”身份驗證方案的授權標頭解析器。

它可以在沒有依賴項的純 node.js 中輕松實現,這是我的版本,它基於express.js 的這個答案,但經過簡化,因此您可以輕松了解基本思想:

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');

您可以使用http-auth模塊

// Authentication module.
var auth = require('http-auth');
var basic = auth.basic({
    realm: "Simon Area.",
    file: __dirname + "/../data/users.htpasswd" // gevorg:gpass, Sarah:testpass ...
});

// Creating new HTTP server.
http.createServer(basic, function(req, res) {
    res.end("Welcome to private area - " + req.user + "!");
}).listen(1337);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM