I am new to Salesforce and my current goal is to ensure that my application never is prompted to give user credentials when making an API call. I see that this is the point of the refresh token, but I'm having some difficulties understanding its workflow:
After reading the documentation, I was under the impression that the refresh access token was something which you generate and store one time. After that, instead of calling services/oauth2/authorize to get a new access_token, you instead pass the stored refresh_token and you no longer need username/password credentials.
This does not seem to be the case. I get the following error when I try to generate a new access_token using my stored refresh_token:
{"error":"invalid_grant","error_description":"token validity expired"}
I did find the setting in the Salesforce UI where you can set the refresh token to expire immediately or after X amount of days, but it will always expire.
How then does the the refresh token workflow work to ensure that your application never needs to log into Salesforce, minus the first time connection?
EDIT: This is how I grabbed the refresh_token:
/**
* Retrieve the refresh token from the API.
*
* @return string
* The refresh token.
*/
public function getRefreshToken() {
try {
$response = $this->client->request('POST', $this->tokenUrl, [
'query' => [
'grant_type' => 'authorization_code',
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
'redirect_uri' => $this->redirectUrl,
'code' => $this->authorizationCode,
]
]);
$response_data = json_decode($response->getBody()->getContents());
}
catch (RequestException $e) {
echo $e->getMessage();
}
return $response_data->refresh_token;
}
I am using this to refresh and reset the access token, which is then used for future calls:
/**
* Refresh the access token using the server side refresh token.
*
* @return $this
*/
protected function refreshAccessToken() {
try {
$response = $this->client->request('POST', $this->tokenUrl, [
'query' => [
'grant_type' => 'refresh_token',
'refresh_token' => $this->refreshToken,
'client_id' => $this->clientId,
'client_secret' => $this->clientSecret,
]
]);
$response_data = json_decode($response->getBody()->getContents());
}
catch (RequestException $e) {
echo $e->getMessage();
}
$this->access_token = $response_data->access_token;
return $this;
}