Thursday, February 21, 2008

Assigning Basic Authorization HTTP Header to HttpWebRequest







If you're making a call to a HTTP resource that requires a Basic Authorization HTTP header, you can use the following code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("url-here");
request.Credentials = new NetworkCredential("username", "password");


Then post the request in the usual way.

The confusion comes because on the first call the HTTP header will not be present on the request. The framework is relying on the first call receiving a 401 response, with a WWW-Authenticate header present, giving a Basic realm=<realm-name> value. A second call will then be made with the correct headers in place.

If you are just consuming the resource, chances are the server will respond in a way that allows this behaviour. However, if it doesn't respond with a 401, or that 401 response doesn't contain the WWW-Authenticate header (or you just don't want to make 2 calls), then you have to manually add the Authorization header to the request:

byte[] authBytes = Encoding.UTF8.GetBytes("user:password".ToCharArray());
request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(authBytes);

8 comments:

Anonymous said...

thanks this sorted it for me,

I was sending a POST to some custom Linux system and needed to use this.

Big help. Cheers.

Anonymous said...

Very helpful....just solved a 502 Bad Gateway problem I had been having unexplicably for the last 2-3 days!

Anonymous said...

Even after setting the authorization header I get a 401 unauthorized. This happens only with the .net code, it works with java code and the browser, any pointers what i might be missing.

Ciaran said...

The server I was posting to did not like the double request (used Fiddler to view). Came back with a 500 Internal Server error which was not very helpful. Stuffed the auth into the header like you suggested and it now only sends one request and works like a charm! Thanks.

Anonymous said...

Thanks a lot

Anonymous said...

Awesome stuff..great help ..Thanks!

Anonymous said...

This helped me out of a big jam. Thanks for posting.

Rameez Ahmed Sayad said...

Thanks nice and crisp explanation.