Digest Authorizarion with Fetch and MongoDb Atlas

Viewed 627

I'm trying to digest authorize the MongoDB Atlas using the Fetch API.

For now I'm doing in this way...

First request:

 const res = fetch(
  "https://cloud.mongodb.com/api/atlas/v1.0?pretty=true",
  {
    headers: {
      Accept: "application/json"
    },
  }
);

Then I receive the response with nonce, realm, qop = "auth" and algorithm = "MD5":

Response {
  url: "https://cloud.mongodb.com/api/atlas/v1.0?pretty=true",
  status: 401,
  statusText: "Unauthorized",
  type_: "default",
  trailer: Promise { <pending> },
  headers: Headers { www-authenticate: Digest realm="XXXXXX", domain="", nonce="4FAFnXrXXXXXXXXXXXXX6dxlXUf", algorithm=MD5, qop="auth", stale=false, content-type: application/json, content-length: 106 },
  body: Body { contentType: "application/json", locked: false, body: [Circular] },
  type: "default",
  redirected: false
}

Now, I do a second request with a MD5 Hash to really authorize it.

How the quality of protection (qop) is equal "auth", I use the bellow logic by rfc2617

In the MongoAtlas Docs says that publicKey is equal username and the privatekey is equal password, then:

const HA1 = md5(`${publicKey}:${realm}:${privateKey}`)
const HA2 = md5(`${method}:${digestURI}`)
const response = md5(`${HA1}:${nonce}:${HA2}`)

I'm not sure what should I put in the digestURI, I think this is it:

const digestURI = "https://cloud.mongodb.com/api/atlas/v1.0?pretty=true"

The Second Fetch Request I made this way:

const digest_header = `username="${publicKey}", realm="${realm}", nonce="${nonce}", uri="${digestURI}", algorithm="MD5", response="${response}", qop="auth"`;


const res2 = fetch(
  "https://cloud.mongodb.com/api/atlas/v1.0?pretty=true",
  {
    headers: {
      Accept: "application/json",
      Authorization: `Digest ${digest_header}`,
    },
  }
);

And still receiving an 401 Unauthorized

UPDATES I fixed the header and it's work! I'm not receiving a 401 anymore. But now I'm receiving an 500 server internal error

Response {
  url: "https://cloud.mongodb.com/api/atlas/v1.0?pretty=true",
  status: 500,
  statusText: "Internal Server Error",
  type_: "default",
  trailer: Promise { <pending> },
  headers: Headers { content-type: application/json, content-length: 48 },
  body: Body { contentType: "application/json", locked: false, body: [Circular] },
  type: "default",
  redirected: false
}

How make it with Fetch? What am I doing wrong?

1 Answers
Related