Using Basic Authentication with Web Services | Salesforce Developers Blog

The requirement to call a web service from with an Apex class is a common use case when using Salesforce.com. Typically this may be a public web service, but at other times there may be a need to use some form of authentication, such as Basic Authentication. Before you cringe at the thought of getting lost in arcane security protocols, don't worry; Apex makes it very easy.

Let's break it down into three simple steps:

Step1: Access HTTP Headers

Thankfully it is very easy to access the http headers in Apex with a few lines of code:

mysample.MySamplePort webservice = new mysample.MySamplePort();
webservice.inputHttpHeaders_x = new Map<String, String>();
Looking at line two above, what we have done is instantiated the input header map on our web service. From here we can add standard or custom headers.

Step 2: Basic Authentication Primer
Next you need to create a Basic Authentication HTTP header. This header takes a name/value pair that takes a user name and password in a base64 encoded string. 

First thing you need to do is set the correct format for your username and password (which is going to become the value in your name/value pair after a little configuration)

myusername:mypassword

Then take this string and convert it to base64. You can use a site such as Base64 Encoder  if you need a quick way to do the conversion. In our example above the encoded string of myusername:mypassword looks like the following after encoding:
bXl1c2VybmFtZTpteXBhc3N3b3Jk
Step3: Add the Authentication Header
Now that we have our encoded string, we need to add the Authentication header to our webservice. Set the value in the name/value pair to Authorization and complete the value like below:

'Basic addYourEncodedStringHere'
Last this is to put it all together, and add the Basic Authentication Header to our input headers:

webservice.inputHttpHeaders_x.put('Authorization', 'Basic bXl1c2VybmFtZTpteXBhc3N3b3Jk');

That's it! You just wrote your first Apex web service call using basic authentication. This was just a very brief introduction to HTTP authentication and web services. If you are looking for more information check out the online Apex docs and the many HTTP Authentication primers on the web.

Stay up to date with the latest news from the Salesforce Developers Blog

Subscribe