HttpWebRequest using Basic authentication

c# httpclient basic authentication example
c# httpwebrequest authorization header
c# call web api with basic authentication
asp.net core 2.0 web api basic authentication
iis basic authentication
c# basic authentication header
create web service with basic authentication c#
how basic authentication works

I'm trying to go through an authentication request that mimics the "basic auth request" we're used to seeing when setting up IIS for this behavior.

The URL is: https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2 (warning: https!)

This server is running under UNIX and Java as application server.

This is the code I use to connect to this server:

CookieContainer myContainer = new CookieContainer();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2");
request.Credentials = new NetworkCredential(xxx,xxx);
request.CookieContainer = myContainer;
request.PreAuthenticate = true;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

(I copied this from another post on this site). But I receive this answer from the server:

The underlying connection was closed: An unexpected error occurred on a send.

I think I tried every possible task my knowledge on C# has to offer me, but nothing...

You can also just add the authorization header yourself.

Just make the name "Authorization" and the value "Basic BASE64({USERNAME:PASSWORD})"

String username = "abc";
String password = "123";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
httpWebRequest.Headers.Add("Authorization", "Basic " + encoded);
Edit

Switched the encoding from UTF-8 to ISO 8859-1 per What encoding should I use for HTTP Basic Authentication? and Jeroen's comment.

You can also just add the authorization header yourself. Just make the name "​Authorization" and the value "Basic  Kerberos must be specially configured to support impersonation. To restrict HttpWebRequest to one or more authentication methods, use the CredentialCache class and bind your credentials to one or more authentication schemes. Supported authentication schemes include Digest, Negotiate, Kerberos, NTLM, and Basic.

I finally got it!

string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
WebRequest request = WebRequest.Create(url);
request.Credentials = GetCredential();
request.PreAuthenticate = true;

and this is GetCredential()

private CredentialCache GetCredential()
{
    string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
    CredentialCache credentialCache = new CredentialCache();
    credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["ead_username"], ConfigurationManager.AppSettings["ead_password"]));
    return credentialCache;
}

YAY!

HttpWebRequest is a handy . NET class for doing HTTP requests. It has built-in support for HTTP basic authentication via credentials. However, it doesn't work the way I expected: supplying credentials doesn't send Authorization HTTP header with the request but only in response to server's challenge. HttpWebRequest with Basic Authentication (C#/CSharp) csharp. This CSharp (C#) code snippet shows how to request a web page using the HttpWebRequest class with basic authentication method enabled. private string LoadHttpPageWithBasicAuthentication ( string url, string username, string password) { Uri myUri = new Uri (url); WebRequest myWebRequest = HttpWebRequest.Create (myUri); HttpWebRequest myHttpWebRequest = (HttpWebRequest)myWebRequest; NetworkCredential myNetworkCredential = new

If you can use the WebClient class, using basic authentication becomes simple:

var client = new WebClient {Credentials = new NetworkCredential("user_name", "password")};
var response = client.DownloadString("https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2");

The response includes a WWW-Authenticate header, indicating the server supports Basic authentication. The client sends another request, with  Basic authentication sends the password across the wire in plain text. That’s okay for a secure connection, such as one using SSL, and for situations where you don’t need much security. Digest authentication hashes the password along with other data from the server before sending a response over the wire.

Try this:

System.Net.CredentialCache credentialCache = new System.Net.CredentialCache(); 
credentialCache.Add(
    new System.Uri("http://www.yoururl.com/"),
    "Basic", 
    new System.Net.NetworkCredential("username", "password")
);

...
...

httpWebRequest.Credentials = credentialCache; 

using Basic Authentication (especially Create(url) as HttpWebRequest; string​  Active Oldest Votes. 80. 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.

For those using RestSharp, it might fail when using SimpleAuthenticator (possibly due to not using ISO-8859-1 behind the scene). I managed to get it done by explicitly sending Basic Authentication headers:

string username = "...";
string password = "...";

public IRestResponse GetResponse(string url, Method method = Method.GET)
{
    string encoded = Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes($"{username}:{password}"));
    var client = new RestClient(url);
    var request = new RestRequest(method );
    request.AddHeader("Authorization", $"Basic {encoded}");
    IRestResponse response = client.Execute(request);
    return response;
}

var response = GetResponse(url);
txtResult.Text = response.Content;

NET WebRequest class does not base64 encode the Authorization header when using HTTP basic Auth. This leads to failing authentication, if your credentials  +1 From MSDN: WebRequest.PreAuthenticate: With the exception of the first request, the PreAuthenticate property indicates whether to send authentication information with subsequent requests without waiting to be challenged by the server, and HttpWebRequest.PreAuthenticate: After a client request to a specific Uri is successfully authenticated, if PreAuthenticate is true

For example, to enable authentication, set the WebRequest.Credentials property to an instance of the NetworkCredential class: request.Credentials = CredentialCache.DefaultCredentials; request.Credentials = CredentialCache.DefaultCredentials Send the request to the server by calling WebRequest.GetResponse. This method returns an object containing the server's response.

Instead you'll have to create the basic auth headers yourself. Basic authentication takes a string that consists of the username and password separated by a colon user:pass and then sends the Base64 encoded result of that. Code like this should work:

// The following example uses the System, System.Net, // and System.IO namespaces. public static void RequestMutualAuth(Uri resource) { // Create a new HttpWebRequest object for the specified resource. WebRequest request=(WebRequest) WebRequest.Create(resource); // Request mutual authentication.

Comments
  • I think this one would have worked if you had added: request.UseDefaultCredentials = false;
  • So how do you know for sure that UTF8 is the right encoding to use?
  • Nice catch. It looks like the request Authentication header should be encoded in ISO-8859-1. Per stackoverflow.com/questions/7242316/…
  • Aaaargh! 1: Thanks, mate. 2. I'd really like to understand why the other methods, setting the authentication method in the CredentialCache, wouldn't work at all. They are supposed to, aren't they?
  • All the msdn documentation points to yes, the other methods should work. However, I've never been able to get them to work.
  • Not working for me (neither utf-8 nor ISO-8859-1). Any suggestions what to check ? It works when I do " webRequest.Credentials = new NetworkCredential(UserID, Password);" .
  • Is it definately basic auth? Also, can you access the resource with your username/password via a browser?
  • It seems to be a basic auth over https. If you click on the link i provided, the browser pop ups the username/password" request as the same do when you do "basic auth" on IIS or using a .htaccss file on a folder via apache. I tried to use fiddler but i have no clue about.
  • i just learned that the website is running under IBM http server. This can be a helpful news?
  • Not working for me (neither utf-8 nor ISO-8859-1 nor default). Any suggestions what to check ?Please note - It works when I do " webRequest.Credentials = new NetworkCredential(UserID, Password);"