views:

84

answers:

3

I am integrating web service that will use an HTTP-POST to request and retrieve data. The remote server requires basic authentication as per RFC 2617

My attempts to authenticate are failing.

It fails in that, even though I attach a 'NetworkCredential' object to the 'Credentials' property of a 'HttpWebRequest' object, no authentication information is sent in the header, even if I set 'PreAuthenticate' = true.

What am I missing?

//chunk used

NetworkCredential netCredential = new NetworkCredential(" uid", "pwd");

Uri uri = new Uri("http://address of services");

ICredentials credentials = netCredential.GetCredential(uri, "Basic");

objRegistration.Credentials = credentials;

objRegistration.PreAuthenticate = true;
+1  A: 

I've just found this very handy little chunk of code to do exactly what you need. It adds the authorization header to the code manually without waiting for the server's challenge.

public void SetBasicAuthHeader(WebRequest request, String userName, String userPassword)
{
    string authInfo = userName + ":" + userPassword;
    authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
    request.Headers["Authorization"] = "Basic " + authInfo;
}

Use it like this

var request = WebRequest.Create("http://myserver.com/service");
SetBasicAuthHeader(request, userName, password);

var response = request.GetResponse();
Samuel Jack
A: 

hi,

using these i made basic authentication.

But how to invoke a method and retrieve output.

Please hlp me.

Regards, Vinay

Vinay
A: 

Vinay use following chunk to get response

WebResponse resp = req.GetResponse();
Stream stm = resp.GetResponseStream();
StreamReader r = new StreamReader(stm);
string myd = r.ReadToEnd();

Himanshu