Salesforce REST API – Refresh Token Integration

I have been googling a lot about the fact how to get a refresh token.
I have rest integration between salesforce to salesforce and it is working fine. After few hours not using the service I get this message in my debug log : message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]
I totally understand why it is happening ( cause every access has some time limit ). Now i want to request for the refresh token ( I understood by reading multiple articles. sample). In order to request for a refresh token, we should pass some parameters as mentioned below.

POST /services/oauth2/token HTTP/1.1
Host: https://login.salesforce.com/ 
grant_type=refresh_token&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0
QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCscA9GE&client_secret=XXXXXXXXXXXXXX
&refresh_token=***your token here*** 

But just wanted to know that from where I get &refresh_token=your token here mentioned in the above sample code.

The rest integration is setup using Named credentials and Auth providers.

As a work around now, when the session is expired every time, I go to connected app and re-authenticate and my code works just fine.

My goal here is, when i face this Session Expired message, i should be able refresh the token withing the same class where i am invoking the rest service so that other piece of logic works fine.
please let me know if anyone has suggestions.

Best Answer

@Eric you are correct. using naming conventions does manages the refresh logic. However i was wrong while selecting the scopes. initially I had selected as follows.

Under Named Credentials ==> Scope = full later changed it to full refresh_token

OAuth remained same.

Connecte App: Selected OAuth Scopes ==> full and refresh_token,offline_access

This solved my problem.

Related Topic