Authenticating to Salesforce using REST, OAuth 2.0 and Java

Posted on 08-01-2013 16:26 by graham
This tutorial will show you how you can authenticate to Salesforce using RESTful services.

Configure remote access in Salesforce

The first thing to do is to allow external applications to connect to Salesforce. External applications will be recognized by two values - client_id and client_secret. In order to generate them, go to Setup | Develop | Remote Access. On the list of Remote Access Applications, click New to create an entry for your external app.

Fill in the form with proper values - they can be whatever you like. We will be using a username and password scenario in OAuth, so the Callback URL field can also have any value whatsoever.

Once you're done filling the form, click "Save". A screen will show up with details of your application. On the bottom of the page there is a section called "Authentication", and there you can find the values of client_id and client_secret which will be of interest to us in the later part of the tutorial.

Calling the login service with REST

In order to obtain an access token, we will send an HTTP POST request to the authentication endpoint exposed by Salesforce. If you are using your production organization, the endpoint's address will be:

If you are connecting to a developer sandbox, use:

The complete code to send to request is:
PostMethod method = new PostMethod("");

HttpMethodParams params = new HttpMethodParams();

StringBuilder content = new StringBuilder();

method.setRequestEntity(new StringRequestEntity(content.toString(), "text/plain", "UTF-8"));
method.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

HttpClient client = new HttpClient();

One thing to remember is that the parameter password is in fact a concatenated value of your password and your security token. It is also essential to set the Content-Type of the request to application/x-www-form-urlencoded.

As a result of this call you should obtain the following response:

You are authenticated. To authorize your calls, use the access_token value received in the response.


Add comment

Has this tutorial been helpful to you? Or do you see anything wrong? We appreciate your opinion!
Your comment:
Show formatting hints
HTML is disallowed, but in your text you can use the following markup
  • [code][/code] for a block of code
  • [tt][/tt] for inline code
  • [link]link href|link anchor[/link] for links
  • [b][/b] for bold text
+ Ask a question
If you have a technical question related to programming and computers, ask it here. Other users will help you solve it!
Unanswered questions
Share your knowledge by helping others solve their problems