Continuing our discussion of integration design patterns, here’s one way to manage OAuth tokens when integrating with external systems. I’ve posted the code so you can follow along.
I recently built an integration from NetSuite to SurveyMonkey Apply (SMA), which uses OAuth 2.0 for authentication. When building integrations, I like to use a Custom Record to hold any configuration parameters for that integration. In SMA, tokens expire every two hours, so we need to store not only the access token information, but also the information for refreshing the access token.
You can see the record I used pictured below.
I’ve previously shown how to turn a custom record into a singleton, and I deploy that same UE to this Configuration custom record. This allows me to make an assumption in my code that only one record of this type exists, and it will always be the first one created (i.e. internal ID = 1).
This assumption allows me to build a module that provides common functions for interacting with the Configuration record.
Now I’ve got a storage mechanism for my token data and a reusable module for reading the token data. I’m ready to build a module dedicated to refreshing the token.
With these three pieces in place, I now have an extremely compact way to validate and refresh my OAuth token for an integration.
Because that refresh logic is contained within a reusable module, I can now leverage it from any entry point in a concise way. In this particular integration, I had an administrative Suitelet which connected a button click to the refresh() method, and I had a Map/Reduce (the core of the integration) which would refresh() during getInputData and would validate() on every reduce().