In my first article on the SFDC REST API I showed how you authenticate to Salesforce using OAuth. The main output of this process is the access token which must be provided when you make any other calls to the REST API. One of the first things I wondered about the access token is, how long does it last? It turns out that the access token is tied to the normal session timeout in SFDC and is configurable for each instance. To view or change the setting log into your account, click Setup, then under Administration Setup select Security Controls then Session Settings.
You can see that in this case the timeout is set to two hours. This means that if you go for more the two hours without calling the REST API the access token will expire. You can change this setting from between 15 minutes and 8 hours.
The next question is, when the access token expires does the user have to go through the login process again? Fortunately the answer is no, this is where the refresh token comes into play. When we did the initial authentication process to get the access token we also received a refresh token. The refresh token can be used to get a new access token without the user having to enter their username and password again.
The code to get a new access token is pretty much the same as the code we initially used to get access token.
You will notice two differences. First instead of passing the code we got when the user logged in, we pass the refresh token, and second we set the grant type to refreshToken instead of authorization_code. The function will return the same response as the initial call did with one exception. According to the OAuth specs the service is not required to return a new refresh token when a new access token is generated. This appears to be the case with SFDC since this call does not return a new refresh token. This means that you need to hold onto the original refresh token to use each time you request a new access token.