[SalesForce] REST API access and refresh token workflow question

I have a cron-job that's running against my SalesForce account daily.

According to my understanding, i can't use the same access token i receive from SF every day for a period of a long time (say a few months), it will expire at some point (according to my policy), right?

So what about the refresh token? Is that the solution i should use?
If i ask SF for a refresh token, it won't expire?

In that case, should i just ask for an access token using my refresh token, try to send my REST API post request with that access token until i see it expires (when i get an error), and then request for a new access token using the refresh token?

Just looking for a clarification.

Thanks!

Best Answer

Refresh tokens have a different policy than access tokens, which are basically session IDs. Access tokens follow the rules for session IDs, meaning they can last up to 24 hours without usage. Conversely, refresh tokens can last indefinitely if configured to do so, and if permitted by the Connected App settings. Assuming you set your refresh token to last indefinitely, your app can use the token indefinitely, even if you change the username or password on the user (but, obviously, not if the user is deactivated or frozen).

However, notice I said that access tokens last until they are not used for a certain period of time. This means you could actually write a second cron job that simply calls "getServerTimestamp" or something periodically (smaller than your expiration time setting) and your access token will remain valid indefinitely. However, since the maximum time is 24 hours, your cron job would be running in to a race condition to use the access token before it expires (~1 second window). If you don't want to keep tabs of a refresh token, it would be slightly more efficient to simply to simply set a cron job that calls the server hourly just to keep the session alive.

As for using the refresh token, you have it basically correct. If you get a 403 error, you request a new access token and try again. You may still want to write additional logic to notify you if the refresh token also expires. This may happen because someone explicitly logs it out in the Session Management or OAuth Session screens.