The.Anti.9
The.Anti.9

Reputation: 44738

Using HTTP Authentication with a C# WebRequest

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.

Upvotes: 27

Views: 56082

Answers (3)

ikutsin
ikutsin

Reputation: 1148

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

Upvotes: 22

Adrian Russell
Adrian Russell

Reputation: 4115

It is also possible to authenticate automatically with. This will use the credentials of the currently logged on user.

webClient.Credentials = CredentialCache.DefaultCredentials

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422242

Assign a new NetworkCredential instance to the Credentials property:

webClient.Credentials = new NetworkCredential("Mehrdad", "Password");

Upvotes: 44

Related Questions