OAuth2 is a magical thing, it makes it *very* easy for users to login to your application without sharing their credentials with it. The actual authorisation of the user is handed over to the service they are authenticating against (e.g Facebook, Twitter, Salesforce) and you are given an ‘access token’ which which you can make requests to the service with. For more on OAuth, there is a good explainer here.

At the moment, I am working on an application that I hope will be useful for some of you. This application needs to authenticate to salesforce in order to use it’s APIs.

The last time I did salesforce auth, I used the Login/Password/Token method via the SOAP API. This method works, but it’s not ideal for a webapp. It’s fairly clunky, requires my app to handle the actual credentials and usually needs a token. It has huge the potential to be insecure and is a bad user experience.

So after much looking around, trying, failing, goolging, etc I finally found something brilliant…. The Scribe library. It handles the actual OAuth bits, this allows my login code to be very, very tiny.

The next piece of the puzzle is what to do with the returned JSON, unfortunately the Scribe library struggles to parse it. In order to access the APIs I am using the Force.com WSC, which uses a ‘ConnectorConfig’ object to pass authentication details when it makes calls. So I needed a way to take the JSON returned from OAuth and return a ‘ConnectorConfig’ object that I can use with the WSC.

This was actually pretty straightforward, I simply serialize the JSON to an object using the Google GSON library and construct the ‘ConnectorConfig’ from the result.

Once I have a connector config, I can make API calls with the WSC and build the rest of my application. I hope that if someone is in the same boat as I was last week that this post helps them out.

Feel free to leave any comments below 🙂

One thought on “Fun with OAuth2

Leave a Reply

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