Httpwebrequest Using Basic Authentication

How to add basic authentication header to WebRequest

Easy. In order to add a basic authentication to your HttpRequest you do this:

string username = "Your username";
string password = "Your password";

string svcCredentials = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(username + ":" + password));

request.Headers.Add("Authorization", "Basic " + svcCredentials);

In basic authentication you need to use Base64 to encode the credentials.

Forcing Basic Authentication in WebRequest

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();

Basic authentication with HttpWebRequest

Edit :

Based on the FaizanRabbani comment, i resolved the problem by setting an UserAgent property to the httpwebrequest :

code :

private async Task<WebResponse> ExecuteHttpWebRequest()
{
var selectedMethode = Methode.SelectedItem as TextBlock;
string method = selectedMethode.Text;
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Query.Text);
WebHeaderCollection myWebHeaderCollection = webRequest.Headers;
myWebHeaderCollection = BuildHeaderCollection(myWebHeaderCollection);
myWebHeaderCollection = AddAuthorization(myWebHeaderCollection);
webRequest.PreAuthenticate = true;
webRequest.Method = method;
webRequest.UserAgent = "something";
if (webRequest.Method == "POST" || webRequest.Method == "PUT" || webRequest.Method == "PATCH")
{
byte[] data = Encoding.ASCII.GetBytes(Body.Text);
webRequest.ContentLength = data.Length;
using (var stream = webRequest.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
return await webRequest.GetResponseAsync();
}



Related Topics



Leave a reply



Submit