Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing Basic Authentication in WebRequest

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; 
like image 861
Himanshu Avatar asked May 04 '10 10:05

Himanshu


1 Answers

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(); 
like image 89
Samuel Jack Avatar answered Sep 28 '22 01:09

Samuel Jack