C sharp .Net 401 error

Trying a basic get using C Sharp code behind on an aspx page and it always returns a 401 (have tried a combo of keys and co numbers). Any ideas why?

WebClient webClient = new WebClient();
webClient.UseDefaultCredentials = true;
webClient.Credentials = new NetworkCredential(“API_KEY”, “”);
Stream stream = webClient.OpenRead(“https://api.companieshouse.gov.uk/company/{co number]”);

1 Like

Looks like you’re not specifying your API key correctly.

If you search the forum (always the first thing you should do IMO :wink:) you’ll find plenty of help, examples and sample code:

http://forum.aws.chdev.org/search?q=authentication%20error

Thanks. Alas though, no sample .net code in my search. Most of the APIs we have used in the past have working code models, not website proof that the auth codes work etc - the documentation doesn’t help much. Should I put a : at the end of the API KEY? IS the password ok as “”? I have tried a few codes but still get the 401.

Our API seems to have stopped returning the www-authenticate header along with the 401. We’ll look at this.

This might be why your .net credential handling is not working - however, IMO it is nasty to have the client wait for a 401 response and a specific header before it will send the credentials. That will result in two trips to the server for each call. Yuck!

Most, if not all other, clients will be explicitly sending the authorisation credentials for every API call, (which is, I suspect, why no one has noticed the disappearance of the www-authenticate response header…).

Credentials are mandatory with our API, so my advice is to force the sending of the Basic authorization credentials and avoid the sending of the unauthorized request first, which will fail every single time! The following may help:

Hope that helps!
Come back for more if you need, and let us know how you get on. Thanks!

C

Thanks for this. I added a header and it now works around the 2 stage auth issue not being implemented (401 / 200)

string credentials = String.Format("{0}:{1}", “API_KEY”, “”);
byte[] bytes = Encoding.ASCII.GetBytes(credentials);
string base64 = Convert.ToBase64String(bytes);
string authorization = String.Concat("Basic ", base64);
request.Headers.Add(“Authorization”, authorization);

We’re considering not implementing the www-authenticate header response to unauthenticated requests.

This will force developers using C# WebClient, and similarly behaved clients, to take matters into their own hands as you have done. This will prevent “optimistic” unauthenticated requests from being sent to the API, when they are doomed to fail, and reduce the server load.