I have problems trying to use custom basic authentication module similar to this. The client uses HttpWebRequest
class.
The client runs the following code:
void uploadFile( string serverUrl, string filePath )
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.
Create( serverUrl );
CredentialCache cache = new CredentialCache();
cache.Add( new Uri( serverUrl ), "Basic", new NetworkCredential( "User", "pass" ) );
request.Credentials = cache;
request.Method = "POST";
request.ContentType = "application/octet-stream";
request.Timeout = 60000;
request.KeepAlive = true;
using( BinaryReader reader = new BinaryReader(
File.OpenRead( filePath ) ) ) {
request.ContentLength = reader.BaseStream.Length;
using( Stream stream = request.GetRequestStream() ) {
byte[] buffer = new byte[1024];
while( true ) {
int bytesRead = reader.Read( buffer, 0, buffer.Length );
if( bytesRead == 0 ) {
break;
}
stream.Write( buffer, 0, bytesRead );
}
}
}
HttpWebResponse result = (HttpWebResponse)request.GetResponse();
//handle result - not relevant
}
If the request is created for a URI starting with http://
it works okay - a request reaches the server, the authentication module is passed the request, it replies with WWW-Authenticate
, the request is repeated now with authentication parameters, the module validates it and it passes further.
If the request is created for a URI starting with https://
it doesn't work. The initial request gets to the module and the module replies with WWW-Authenticate
void ReplyWithAuthHeader()
{
HttpContext currentContext = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.AddHeader( "WWW-Authenticate",
String.Format("Basic realm=\"{0}\"", "myname.mycompany.com"));
}
an an exception is thrown at the client with "Unable to write data to the transport connection: An established connection was aborted by the software in your host machine." text.
I tried System.Net tracing and discovered that after sending the initial request the client gets back the following header:
Date: Fri, 04 Feb 2011 12:15:04 GMT
Server: Microsoft-IIS/5.1
X-Powered-By: ASP.NET
while when the URI started with http://
the client received the following:
Content-Length: 1894
Cache-Control: private
Content-Type: text/html; charset=utf-8
Date: Fri, 04 Feb 2011 12:12:11 GMT
Server: Microsoft-IIS/5.1
WWW-Authenticate: Basic realm="myname.mycompany.com"
X-AspNet-Version: 2.0.50727
X-Powered-By: ASP.NET
so clearly the WWW-Authenticate
response is swallowed somewhere and doesn't reach the client.
Also if I exclude the code that writes the file data into the request it also authenticates okay.
How do I fix this? How do I make the WWW-Authenticate
response get to the client?