在Node.js中的摘要认证

3
我正在使用urllib npm包,以下是我的代码:
options = {
    method: 'GET',
    rejectUnauthorized: false,
    digestAuth: `${user}:${pass}`
}

urllib.request(uri, options, function (err, data, res) {
    if (err) {
        throw err; // you need to handle error
    }
    console.log(res.statusCode);
    console.log(res.headers);
    // data is Buffer instance
    console.log(data.toString());
})

很不幸,我收到了一个401错误:

401 { 'content-length': '222', 'content-type': 'text/plain',
connection: 'close', 'www-authenticate': 'Digest realm="000f7c16eacc", nonce="8652e7dfa50f6124896b84142eef93b5", stale="false", algorithm="MD5", qop="auth"', 'x-frame-options': 'SAMEORIGIN' } { "Response": { "ResponseURL": "/images/snapshot.jpg", "ResponseCode": 3, "SubResponseCode": 0, "ResponseString": "Not Authorized", "StatusCode": 401, "StatusString": "Unauthorized", "Data": "null" } }

当通过postman访问时,相同的uri、用户名和密码可以正常工作。我在这个请求中缺少哪些配置细节?urllib没有提供摘要认证示例。

我没有使用urllib,我将接受任何能够从摘要认证端点拉取图像的nodejs解决方案。


从您收到的响应来看,您的代码似乎没有任何问题。获得http 401意味着您的凭据无效。 - artfulbeest
1个回答

1

你的代码应该按照类似问题的推荐答案工作。

你确定你的用户名和密码是正确的吗?

使用urllib

以下代码示例对我来说完美地工作。只有当用户名和密码不正确时,我才会遇到与你相似的错误。

client.js

const httpClient = require("urllib");

const user = "ankit";
const pass = "ankit";

const uri = "http://localhost:1337";
options = {
  method: "GET",
  rejectUnauthorized: false,
  digestAuth: `${user}:${pass}`,
};

httpClient.request(uri, options, function (err, data, res) {
  if (err) {
    throw err; // you need to handle error
  }
  console.log(res.statusCode);
  console.log(res.headers);
  // data is Buffer instance
  console.log(data.toString());
});

server.js

var http = require("http");
var auth = require("http-auth");

var digest = auth.digest({
  realm: "Sample",
  file: __dirname + "/users.htpasswd",
  algorithm: "md5",
});

http
  .createServer(
    digest.check((req, res) => {
      res.end(`Welcome to private area - ${req.user}!`);
    })
  )
  .listen(1337, () => {
    // Log URL.
    console.log("Server running at http://127.0.0.1:1337/");
  });

users.htpasswd

ankit:Sample:e4b2d19b03346a1c45ce86ad41b85c5e

示例代码


用户名和密码正确。我使用请求库解决了这个问题(这个库因为“太受欢迎”而被奇怪地弃用了)。虽然我从未能让URLLIB正常工作,但我会尝试复制粘贴你的代码来验证。 - lowcrawler
以上代码的复制/粘贴未能奏效。但是没有其他人回答,所以我还是给了你赏金。 - lowcrawler
谢谢,但我很惊讶它没有起作用。这就是为什么我把它粘贴过来的。:\ - indolentdeveloper

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接