I want to make a web request to a page that needs authenticating. How would I go about doing this? I found something that said possibly to use the Credentials property, but I'm not sure how to use it.
Asked
Active
Viewed 5.6k times
3 Answers
44
Assign a new NetworkCredential
instance to the Credentials
property:
webClient.Credentials = new NetworkCredential("Mehrdad", "Password");

Mehrdad Afshari
- 414,610
- 91
- 852
- 789
-
1This didn't work for me, but ikutsin's answer setting the "Authorization" header explicitly with Basic auth info did work for me. – markshep Oct 24 '16 at 13:16
-
1Both methods (credentials and adding header) are works. But i don't really get which one is better and why? – Archont Jan 24 '17 at 06:37
22
Basic auth example:
public void SetBasicAuthHeader(WebRequest req, String userName, String userPassword)
{
string authInfo = userName + ":" + userPassword;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
req.Headers["Authorization"] = "Basic " + authInfo;
}
http://blog.kowalczyk.info/article/at3/Forcing-basic-http-authentication-for-HttpWebReq.html

ikutsin
- 1,118
- 15
- 22
-
Good point here. The extra chattiness that this avoids can also be a performance problem. – tallseth Dec 23 '13 at 12:51
3
It is also possible to authenticate automatically with. This will use the credentials of the currently logged on user.
webClient.Credentials = CredentialCache.DefaultCredentials

Adrian Russell
- 3,995
- 5
- 25
- 26