[SalesForce] Salesforce OAuth 2.0 JWT Bearer Token Flow – Token Expiration

I am performing Server-Server communication between Salesforce and a Portal I am developing.

I implemented the JWT Flow as follows:

  • Created connected app and digitally signed it with certificate
  • Implemented JWT get authentication token: I am sending authentication request and I am getting back an access_token
  • I am using the access token to communicate with salesforce (create, update, get,…)

But the access_token is getting expired daily. How I can make this token serve for ever, or at least for a very long time.

Best Answer

The length of time that your access token is valid is determined by the session timeout value in the Connected App's policies. By default, I believe that this timeout is not set, in which case the Connected App defaults to the session timeout policy of your target org (Setup -> Security -> Sessions Settings in LEX).

The session timeout is reset every time you make a request with a given access token, so if your portal is active enough, you don't really need to worry about it.

This approach, however, sacrifices security. Better practice, I believe, would be to set a very short timeout, and assume that your access token is always invalid and go through the JWT flow for each request. If the access token isn't expired yet, going through the JWT flow will return the same token.

An alternative approach would be to try to make a request using the current token, handling the auth error (if one is returned), and using that as your indicator to make request for a new access token.