'Digest authentication in nodejs
I'm using the urllib npm package with the following code:
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());
})
Unfortunately, I'm getting a 401 error back:
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" } }
The same uri, username, and password works when accessing via postman. What configuration details am I missing in this request? urllib doesn't provide a digest auth example.
I am not married to urllib and will take any working nodejs solution for pulling an image from an digest-auth endpoint.
Solution 1:[1]
Your code should work as it is recommended answer for similar questions.
Are you sure your user name and password is correct ?
Following code sample works perfectly for me. only when username and password is incorrect then I get similar error as you.
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
