Salesforce

Establishing OAuth Credentials with Salesforce

Adrian Wright

Introduction

As discussed in my last post, a strong understanding of OAuth is critical to the success of your Salesforce API integration project.  In this post, I'll show you how to set up OAuth communications.

Before you get started...

  1. Doing this for the first time, you will want an easy-to-use REST client.  You will exchange data with Salesforce via HTTP headers and JSON.  You'll want to easily be able to create HTTP requests and view JSON responses, especially if an error is returned.  Salesforce can throw a 400 Bad Request for many different reasons.  I like to use Postman in Chrome.
  2. Get the password for at least one of the accounts you want to use to log in to Salesforce.  This will get you through the process for the first time.  If your app needs to log in as many different users, you should automate the process at least from Step 3 to the end, so the user can initiate access from within your application.

Step 1:  Set Up A Custom Endpoint

Salesforce will send you an authorization code as one step of the OAuth process.  As a result, you need an endpoint for Salesforce to call.  Understanding this was my first "aha" moment in learning the OAuth process.  Communication is actually initiated by both sides, at different times in the process.

In C#, this could be an MVC or WebAPI controller action.  The important part is that the endpoint has a URL you can provide to Salesforce:

 public ActionResult Authorize()
 {
     string authorizationCode = Request["code"];
     // Write the authorization code to a log file here
 }

Regardless of your language, look for the code in a header called "code".

Note: The URL does NOT need to be publicly accessible, for the purposes of your initial test. Salesforce will call it from JavaScript code in your web browser, so there's no need to jump through hoops to make it public.  If you are integrating the OAuth configuration process in your application, then you will need a publicly accessible URL.

Step 2:  Create a Salesforce Connected App

A connected app opens the Salesforce API to your application.  You can set the privileges that the app can have, and it will give you the credentials you need to create your OAuth tokens.

Follow these steps to create a Connected App.  Be sure to research the different permission levels, to ensure that you have given your app the appropriate level of permissions.

When you're done, you should have a Consumer Key and Consumer Secret to use in the next step.

 

Step 3:  Create Access for a Salesforce User

As discussed in my last post, your app must act on behalf of a Salesforce user.  In some cases, you may act as different users at different times, depending on the needs of your application.  You must repeat steps 3 and following for each user that your application will use.

Create a web request in a browser to https://test.salesforce.com/services/oauth2/authorize using these URL parameters:

  • response_type:  code
  • redirect_uri:  (your URL from Step 1, be sure to URL-encode it!)
  • client_id:  (your Consumer Key from Step 2)

Your complete URL might look something like this (the client_id below has been replaced with a random string):  

https://test.salesforce.com/services/oauth2/authorize?response_type=code&client_id=Ng7p2DkhAhwg8KtUlHTH4PSUIRrsUJEY5gFtYOilytrEOzmel1chq1YAjeGlbQEzIroETG279W&redirect_uri=https%3A%2F%2Flocalhost%2FMyApp%2FAuthorize

At this point you will be prompted to log in to Salesforce.  Log in as your Salesforce user.

Immediately you will be given the option to ALLOW or DENY the app to log into the Salesforce API as your user.  Click ALLOW.

Salesforce will now call your URL from Step 1, supplying you with the Authorization Code that you need to get your OAuth tokens.  Be sure to collect the authorization code by writing it to a log or database.

Note:  use login.salesforce.com if you are doing this in a production environment.  test.salesforce.com is for the sandbox.

Step 4:  Create your Refresh Token and Access Token

Now that you have your Authorization Code, you can create your OAuth Refresh and Access Tokens.

A little about the tokens:

  • Each user has unique refresh and access tokens
  • Depending on configuration, the Refresh Token is valid indefinitely, for a specific period of time, or it can be manually revoked by an admin.
  • Access tokens expire frequently.  Salesforce does not give you an expiration time, so many apps look for an expired token exception, and initiate the logic for requesting a new Access Token.  Read more about it here.

You're going to use your REST client for this step.  Construct a request to https://test.salesforce.com/services/oauth2/token that has these parameters:

  • grant_type: authorization_code
  • code: (your code from Step 3)
  • client_id:  (your Consumer Key from Step 2)
  • client_secret:  (your Consumer Secret from Step 2)
  • redirect_uri:  (your URI from Step 1 URL ENCODED!)

Your final request might look something like this:

https://test.salesforce.com/services/oauth2/token?grant_type=authorization_code&codegsKagMddFxAATQZH7V5Ul9PZp-8Z225351Se9wvNbbw3wTLkjaE=&client_id=Ng7p2DkhAhwg8KtUlHTH4PSUIRrsUJEY5gFtYOilytrEOzmel1chq1YAjeGlbQEzIroETG279W&client_secret=362364322265342&redirect_uri=https%3A%2F%2Flocalhost%2FMyApp%2FAuthorize

You will receive a JSON response.  Store the id, refresh_token and access_token fields.

Here are common pitfalls with this step:

  • Using the wrong endpoint -- use test.salesforce.com for sandbox and login.salesforce.com for production.  All connected apps and OAuth credentials are environment-specific.
  • URL from Step 1 doesn't exactly match the one you configured in the Connected App, or isn't URL encoded
  • Stale Authorization Code -- if this occurs, start over with a new authorization code.

Step 5:  Get the SOAP URL to use

Now that you have your access token, you can request the SOAP URL to use for your actual business data calls.  

Use the URL from the id parameter that you collected in Step 5 as the base URL.  Pass one parameter called "oauth_token" with your access token.  Your final URL might look like this (I've substituted a random string for the access token):

https://test.salesforce.com/id/00AS000000DJucQQAX/00420000007dA9SSAR?oauth_token=bQEzIroETG279WHJ87xdk9LC5ZIEqnSdhsktaTci4kxoqpsvRaqqMRKRZiYyWWXl3bq9glDszYmxeIFPrUmvIBuKKu9LWp1lvzPn

You will get a JSON response with a field called "urls". Inside this object, grab the "enterprise" field, which contans your SOAP URL.

Note:  You will notice the URL has a replacement token in it, "{version}".  Replace this with the API version that you plan to use.  (e.g. 30.0, 31.0, etc.).

Step 6:  Use Your Access Token (while you still can)!

The Access token is included in all calls to the API as your SessionId.  After a period of time, you will receive an error indicating that the token is expired.  To refresh your token, create a new HTTP request with these headers:
  • grant_type: refresh_token
  • client_id
  • client_secret
  • refresh_token
  • format:  json

You will receive a json response with a field called "access_token".  Store this token and use it until it expires.

In Conclusion

Here are some things to remember as you implement this process:

  • Automate!  Automate as much of this process as you can, to save yourself time and reduce the need for manual intervention.  How much you automate will really depend on the needs of your application.  At minimum, your app has to be able to refresh its access token automatically.  You may find it is helpful to automate more than that.
  • Remember the scope of your tokens.  The client key and client secret are application-wide.  Refresh tokens and access tokens are per-user.
  • Connected apps, settings, and tokens that work in production do not work in the sandbox and vice-versa
  • Refreshing your sandbox from production will delete your Connected App.  This is another reason to automate, because you will need to re-do this process in the sandbox after each refresh..

That's all, folks!  Post a question if you have one.

Adrian Wright
ABOUT THE AUTHOR

Distinguished Technical Consultant