Skip to content

How-to: Calling Web Services Using Basic Authentication

How-to: WebMethods Call Using Basic Authentication

I recently made a web services call into WebMethods using basic authentication.  This authentication meant that we needed to modify the WSDL-generated classes to handle the authentication.

Here’s how it works.  I add a reference to the Web Service (Visual Studio generates the client code for calling the web service).  Then, to this generated class I need to add the following method:

protected override System.Net.WebRequest GetWebRequest(Uri uri) { HttpWebRequest request; request = (HttpWebRequest)base.GetWebRequest(uri); if (PreAuthenticate) { NetworkCredential networkCredentials = Credentials.GetCredential(uri, "Basic"); if (networkCredentials != null) { byte[] credentialBuffer = new UTF8Encoding().GetBytes( networkCredentials.UserName + ":" + networkCredentials.Password); request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer); } else { throw new ApplicationException("No network credentials"); } } return request; }
Code language: PHP (php)

This overrides the GetWebRequest() <code> method of the </code> System.Web.Services.Protocols.SoapHttpClientProtocol class that the web service client code derived from.

With Visual Studio 2005 the generated code is a C# 2.0 partial class.  As a result, regenerating the web services client code does not over-write the additional method.  To enable this, add a class file to your project and give it the same namespace and name as the generated  System.Web.Services.Protocols.SoapHttpClientProtocol <code> derived class.  The key is to use the partial modifier on the class header so that the </code> GetWebRequest() <code> method is added to the generated class.  (</code> partial class Michaelis.MockService{...} )

Regardless of using Visual Studio.NET 2005 or earlier, the client code requires that the network credentials are set and the  PreAuthenticate property is assigned true.  Here is a sample client call:

Michaelis.MockService service = new Michaelis.MockService(); // Create the network credentials and assign // them to the service credentials NetworkCredential netCredential = new NetworkCredential("Inigo.Montoya", "Ykmfptd"); Uri uri = new Uri(service.Url); ICredentials credentials = netCredential.GetCredential(uri, "Basic"); service.Credentials = credentials; // Be sure to set PreAuthenticate to true or else // authentication will not be sent. service.PreAuthenticate = true; // Make the web service call. service.Method();
Code language: JavaScript (javascript)

UPDATE for Calling Web Services

Comments on the post raised the question, “Why can’t you just say request.Credentials = new NetworkCredential(username,password).”

The reason relates to interoperating with WebMethods specifically.  When just setting Credentials , the HTTP header looks like this:

POST /soap/rpc HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50113.0) Content-Type: text/xml; charset=utf-8 SOAPAction: "" Host: <servername>:<port Content-Length: 779 Expect: 100-continue Accept-Encoding: gzip
Code language: PHP (php)

Notice, that there is no Authentication item even though PreAuthenticate is set to true.

The reply back from WebMethods is as follows:

HTTP/1.0 500 Internal Server Error Set-Cookie: ssnid=11747k5Rwchr3vW0s23vcaCP1wCA2NDc=555590; path=/; Content-Type: text/xml;charset=utf-8 Connection: Keep-Alive Content-Length: 849
Code language: HTTP (http)

The problem is that .NET is expecting a challenge response from WebMethods, specifically a 401 error of “Invalid credentials.”  However, if the client’s credentials are not specified (there is no Authentication part to the header) then WebMethods returns an HTTP 500 status code (Internal Server Error) indicating that the request could not be fulfilled.

To fix the problem you can either change the .NET client or else the WebMethods server.  In my original posting, I demonstrated how to control the .NET client.  The result was an HTTP header that includes the Authentication portion as shown below:

POST /soap/rpc HTTP/1.1 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50113.0) Authorization: BasicbGRwcm86bGRwcm8= Content-Type: text/xml; charset=utf-8 SOAPAction: "" Host: spo-wm-py-srvr:5555 Content-Length: 779 Expect: 100-continue Accept-Encoding: gzip
Code language: JavaScript (javascript)

However, it is also possible to change the WebMethods side (assuming you control that side) by creating an access-controlled SOAP processor that checks the credentials for each client request against a specified ACL and returns an HTTP 401 status code even if there are no credentials passed.

By the way, the tool I use for tracing HTTP is YATT.

Want More?

Check out this blog on fully-managed passwordless authentication!

38 thoughts on “How-to: Calling Web Services Using Basic Authentication”

  1. Thanks a lot Mark for this wonderful post. first time the code didn’t work. But after going through all comments I figured it out that a space is required after the Basic word. Once I made that change it worked. Will it be possible for you to update the code sample to include that extra space required. This will help others also and saves time who just copy and paste your code.

    Thanks again.

  2. hi,
    This is great.
    can you please let me know how to add ws-Security Header?


  3. Hi,

    I am getting error message:
    SoapHeaderException: Bad auth String (could not parse username/password): String index out of range: -1

    please help

  4. This is FANTASIC!!! I wish I would have read Rich Jardine’s comments first. I got it working by using “Basic ” + Convert.ToBase64String(credentialBuffer);

  5. Hi,

    I have implemented the code suggested here but it is not working, can someone please suggest if I need to change anything to make it work.

  6. hi, i am using remedy itsm 7.6.03
    while consuming a web service it shows a error the request failed with HTTP status 505 version not supported.
    plz help me to solve this.

  7. Hi mark, this article is really helpful. I want to configure client to send credentials for each request. You said "In my original posting, I demonstrated how to control the .NET client." Can you please share me the link for configuring client? Thanks in advance.

  8. Mark,
    I’ll add my thanks to all the others. I was having trouble connecting with an HP Service Manager Web Service ( Apache ) from a .NET client. The HPSM process dies on the UNIX box without the preauthentiation header. I wasted a lot of time until I found this post on your blog. You are steely eyed coder man. Many thanks!!!

    Best Regards,

    I only had to modify one line of your function:
    "Basic" + Convert.ToBase64String(credentialBuffer);
    "Basic" + "\t" + Convert.ToBase64String(credentialBuffer);

    1. Hi,
      Even i want to connect to HPSM Incident Management Web Service to Create Incident.

      I am getting error message:
      SoapHeaderException: Bad auth String (could not parse username/password): String index out of range: -1

      please help

  9. Helpful post!

    Is there any way to force BASIC authentication from the client app? For example if IIS is configured for both BASIC and INTEGRATED authentication and the Client app can authenticated using INTEGRATED however you want to explicitly override this using BASIC authentication how can this be achived?



  10. Another poor soul that’s been saved by your blog post, Mark! However, I had to insert a space between "Basic" and the BASE64 encoded credentials string, but maybe that’s just me.

    Anyway, thanks a million! :D

  11. Thanks for the post! My collegue and I were going nuts for almost over 2 weeks trying to figure what was the problem with authentication!

    Thanks again,

    eliseu martinho

  12. Thank you very much!
    I spend days to investigate that problem!
    You should tell this the guys at webmethods, because the forum is full of threads with that problem!

    Thank you!!!

  13. I’ve tried the code and it works but only for the first call. If I make a second call, I get an exception, "The underlying connection was closed: An unexpected error occurred on a send". You have any ideas? THanks.

  14. I just wanted to say thank you so much for this method. It was literally driving me bonkers. You have been so much help, and I sincerely appreciate it.

  15. Many, many, many thanks. It took me the whole day to finally find the solution to this problem on your site. As I said: Many thanks :-)

    A little suggestion: I wouldn’t change the autogenerated code, instead I subclassed the generated class and added the code there. So it is safe to update the webservice at a later point.

  16. Great post saved me lots of time thanks!

    To get the code to work I did have to make a slight change which was to simply add a space ("Basic ") to the following line:

    request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(credentialBuffer);

  17. Just wanted to say thanks!

    Me and my team have been looking into it for over a week now and it was royally driving us nuts!

    Bleedin’ ‘ell, what a relief…

    Thanks a million!

  18. What happens if the webservice is secure? I’ve never used 2005, so I’m assuming this is simlar to httpWebRequest? When I have had authenticate I have always used the method above. (Maheshwar’s)

    Good stuff Mark.

  19. I am surprised why you had to manually send a basic authentication header with the request.

    Why cant you just say
    request.Credentials = new NetworkCredential(username,password)

    or if you want to use your windows logged on user identity

    request.Credentials = CredentialCache.DefaultCredentials

Leave a Reply

Your email address will not be published. Required fields are marked *