network Authentication and website Authentication using HttpWebRequest

I am trying to create a application that will consume RSS data using .NET Framework. The RSS site requires User name and Password to start with.
and Am running this application from within my work place which requires NTLM authentication to connect to internet.

Following is the code that i am trying to use

NetworkCredential nc = new NetworkCredential("SITEUSERNAME", "SITEPASSWORD");
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(RSSFeed), "Basic", nc);
cache.Add(new Uri(RSSFeed), "Ntlm", new NetworkCredential("USERNAME","PASSWORD","DOAMIN"));
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RSSFeed);
myHttpWebRequest.Proxy.Credentials = cache;
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();

i get 407 error and if i simply use CredentialCache.DefaultNetworkCredentials i get 401 error.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

solved the issue by using following code

 string credentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes("UserName" + ":" + "Password"));
 StringBuilder outputData = new StringBuilder();
 HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RSSFeed);
 myHttpWebRequest.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
 myHttpWebRequest.Headers.Add("Authorization", "Basic " + credentials);
 HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
 Stream streamResponse = myHttpWebResponse.GetResponseStream();

Method 2

If this code works, then your original code above was wrong. You should set

request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;

and

NetworkCredential nc = new NetworkCredential("SITEUSERNAME", "SITEPASSWORD");
CredentialCache cache = new CredentialCache();
cache.Add(new Uri(RSSFeed), "Basic", nc);
cache.Add(new Uri(RSSFeed), "Ntlm", new NetworkCredential("USERNAME","PASSWORD","DOAMIN"));
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(RSSFeed);
myHttpWebRequest.Credentials = cache;

In other words, you had exchanged credentials for the proxy and the destination server.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x