HttpClientHandler does not work for authentication
using (HttpClientHandler handler = new HttpClientHandler
{
Credentials = new NetworkCredential(sUserName, sPassword),
UseDefaultCredentials = false,
PreAuthenticate = true
})
{
using (HttpClient hc = new HttpClient(handler))
{
Stream stream = await hc.GetStreamAsync(new Uri(sURL)).ConfigureAwait(false)
}
}
The above code throws HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
I used WireShark and found HttpClient just repeats the following:
GET /foo/media_service/snapshot?channel=1&subtype=1 HTTP/1.1
Host: 192.168.1.230
Connection: Keep-Alive
Cache-Control: no-cacheHTTP/1.1 401 Unauthorized
Connection: close
WWW-Authenticate: Digest realm="Login to AMC047BC0E5D7225F6",qop="auth",nonce="b252aWYtZGlnjQzNjQxOTg5MTEw", opaque="", stale="false"
Could anyone shed some light on this?
[Edit] 2020-09-12
If I use Chrome to browse the same URL, I get the following:
GET /foo/media_service/snapshot?channel=1&subtype=1 HTTP/1.1
Host: 192.168.1.230
Connection: keep-alive
Cache-Control: max-age=0
Authorization: Digest username="admin", realm="Login to AMC047BC0E5D7225F6", nonce="b252aWYtZGlnjQzNjQxOTg5MTEw", uri="/foo/media_service/snapshot?channel=1&subtype=1", response="1675d571737d9263f35b00ced5b4ed00", qop=auth, nc=00000002, cnonce="2b1d294b246a6e6c"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7HTTP/1.1 401 Unauthorized
Connection: close
WWW-Authenticate: Digest realm="Login to AMC047BC0E5D7225F6",qop="auth",nonce="b252aWYtZGlnjQzNjQxOTg5MTEw", opaque="", stale="true"
Content-Length: 658GET /foo/media_service/snapshot?channel=1&subtype=1 HTTP/1.1
Host: 192.168.1.230
Connection: keep-alive
Cache-Control: max-age=0
Authorization: Digest username="admin", realm="Login to AMC047BC0E5D7225F6", nonce="b252aWYtZGlnjQzNjQxOTg5MTEw", uri="/foo/media_service/snapshot?channel=1&subtype=1", response="3e978997a7d74ba3144e75e0f662997c", qop=auth, nc=00000001, cnonce="414ad418d6d1455d"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Transfer-Encoding: binary
Content-Length: 227512
Connection: close......JFIF.............C...........