Satish Vemula

in

Sending Http Authentication Request from a Windows Form

 

If you need to perform authentication using HttpWebRequest from a Windows application, you can do it the following way:

 

// Prepare the data that needs to be sent

string postData = "userID=" + HttpUtility.UrlEncode(userID);

postData += "&password=" + HttpUtility.UrlEncode(_password);

byte[] data = ASCIIEncoding.ASCII.GetBytes(postData);

 

// Prepare web request

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(myURL);

 

// Add the required headers

webRequest.Method = "POST";

webRequest.ContentType = "application/x-www-form-urlencoded";

 

// Since we are sending data, specify the content and write to the stream

webRequest.ContentLength = data.Length;

Stream newStream = webRequest.GetRequestStream();

// Send the data.

newStream.Write(data, 0, data.Length);

newStream.Close();

 

// Retrieve the response

HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

XmlTextReader reader = new XmlTextReader(webResponse.GetResponseStream());

XmlDocument doc = new XmlDocument();

doc.Load(reader);

 

// And then read the XmlDocument

 

The above immplementation is pretty straightforward. If you plan to send the credentials in the header, you can use Basic Authentication. This should only be used when sending the request over SSL as the information is still sent openly. Using SSL ensures that the contents of this request are encrypted. This can be done in the following way:

 

//Prepare the Authentication parameters

String auth = userID + ":" + password;

byte[] binaryData = Encoding.UTF8.GetBytes(auth);

auth = Convert.ToBase64String(binaryData); // Using base64 encoding

auth = "Basic " + auth; //This specifies it to use Basic Authentication

 

// Prepare web request

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(myURL);

 

// Add the standard headers

webRequest.Method = "POST";

webRequest.ContentType = "application/x-www-form-urlencoded";

webRequest.ContentLength = 0;

 

// Add this additional header

webRequest.Headers[“AUTHORIZATION”] = auth;

 

HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

XmlTextReader reader = new XmlTextReader(webResponse.GetResponseStream());

XmlDocument doc = new XmlDocument();

doc.Load(reader);

 

This is a more secure call!

 

You can find more information about HttpWebRequest and Headers at:

 

http://msdn2.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

 

http://msdn2.microsoft.com/en-us/library/system.net.httpwebrequest.headers.aspx

 

 

Comments

Hammadi said:

Thunk you for this helpful post
Regards
# January 2, 2007 6:20 AM

Mark said:

Thanks for the info. I was trying to do it by using HttpWebRequest.Credentials, which I would have thought should work and relieve the developer from having to add the auth header manually.

# February 14, 2008 5:02 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)