简体   繁体   中英

Authentication to REST API: digest type with cookie (c#)

I have a service REST API where I tryied to connect. Using browser all is ok.

But in c# I always have an unauthorized answer.

I investigated this issue using fiddler and find out that in first unsuccessful reuest server returns some cookie, and browser use it in next session together with username/password (digest type).In this case second session is successful.

But when I try to send request using c# (I tried work with System.Net.WebClient and HttpWebRequest) I don't get response (I had timeout exception after some time).

My code:

WebClient webClient = new WebClient(); 
CredentialCache cache = new CredentialCache();
Uri prefix = new Uri(Url);
cache.Add(prefix, "Digest", new NetworkCredential(login, password));
webClient.Credentials = cache;
...

string response = webClient.DownloadString(restRequest);

Last line throws exception.

When I investigated this issue in Fiddler I found out that in first session with status 401 we recieved cookie (like on picture below). fiddler's picture Browser sends this cookie in next request and authentication happens successfully. But in c# I couldn't geet this response with status 401. As I see in fiddler studio try to open new session 10-20 times during each next seconds before timeout exception will be thrown. And my response in null.

Also I have other environment without required cookie, there my code is working.

Please, give me a piece of advise hoe to get response with Status 401 and get cookie from it to set it to another request.

thanks Mike

I resolved this issue using HttpWebRequest with defined empty (not null) CookieContainer.

My code:

HttpWebRequest request1;
HttpWebResponse response1 = null;
String responseBody;
request1 = (HttpWebRequest) WebRequest.Create(requestString);
request1.Credentials = cache;

request1.CookieContainer = new CookieContainer();            

response1 = (HttpWebResponse) request1.GetResponse();
using (StreamReader stream = new StreamReader(response1.GetResponseStream(), Encoding.UTF8))
    {
        responseBody = stream.ReadToEnd();
    }

In this implementation after first session with status 401 requests provide cookie from first session to next one and it returns with status code 200 OK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM