So I've been working to persist a logged-in Users session without the user having to log back in. This would be done with the "OAuth 2.0 Refresh Token Flow". However, I'm having trouble mapping out how this would be done in Apex.

Right now, I am trying to use Apex HTTP request to "https://test.salesforce.com/services/oauth2/token" and "https://test.salesforce.com/services/oauth2/token" with the client ID, Client Secret and redirect URI to the connected app. I've had success using PostMan but need this be done in the background of the app using Apex code. Is there a way to do this?

  • 1
    Have you tried using named credentials? It would made all the login and token refresh transparent to you help.salesforce.com/… Oct 25, 2017 at 21:12
  • I'll give that a try Sergio. I'll report back if it works or not. Thank you
    – MMeadows
    Oct 25, 2017 at 21:16

1 Answer 1


Last year I had to build an Oauth2 process from scratch because the external app didn't support any of the protocols of the Named Credentials. The project never rolled out to production, but I did get it working in the sandbox. Here's what I did:

Set up custom settings to hold the access token, the refresh token, and a timestamp. The timestamp marks the last refresh.

When a user tries to access the external app and the access token is blank, do the initial access token HTTP request. The external app should redirect to your VF page with the access token and refresh token. At this point, write the tokens and the timestamp to the custom settings.

When a user tries to access the external app and the access token exists but the timestamp has expired, then do the refresh token HTTP request and write the new values to custom settings.

  • I believe best practice is to implement a refresh flow if the access token is rejected rather than looking at a time stamp.
    – Eric
    Oct 26, 2017 at 3:47
  • I think I had a reason for checking timestamp instead of checking for rejected access token, but I can't remember now. Oct 26, 2017 at 22:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .