[SalesForce] Receiving invalid error messages in Apex for failing to specify a refresh token (Oauth2)

I'm running into an issue where I am receiving error messages after starting the authentication flow in my Named Credential and Apex code where my authentication provider didn't receive a refresh token from my external source. I normally generate the refresh token myself with the external source, however I don't see a spot in the SF Auth. Provider or Named Credential settings to store it. How would I keep and utilize my external source's refresh token in SF since the refresh token itself doesn't expire?

Named Credential error message:

The authentication provider didn't provide a refresh token. If the
access token expires, your org won't be able to access this named
credential.

Apex Raw Log output:

43.0 APEX_CODE,FINE;APEX_PROFILING,NONE;CALLOUT,NONE;DB,NONE;NBA,INFO;SYSTEM,NONE;VALIDATION,NONE;VISUALFORCE,NONE;WAVE,NONE;WORKFLOW,NONE
Execute Anonymous: AuthCallout.basicAuthCallout();
10:19:48.1 (1119358)|USER_INFO|[EXTERNAL]|00xx000000xxxxx|user@corporation.com.user|Eastern Standard Time|GMT-04:00
10:19:48.1 (1139619)|EXECUTION_STARTED
10:19:48.1 (1144456)|CODE_UNIT_STARTED|[EXTERNAL]|execute_anonymous_apex
10:19:48.1 (15839897)|METHOD_ENTRY|[1]|000000000000000|AuthCallout.AuthCallout()
10:19:48.1 (15876984)|METHOD_EXIT|[1]|AuthCallout
10:19:48.1 (15909222)|METHOD_ENTRY|[1]|000000000000000|AuthCallout.basicAuthCallout()
10:19:48.1 (257227020)|USER_DEBUG|[12]|DEBUG|{
  "error": {
    "code": "InvalidAuthenticationToken",
    "message": "CompactToken parsing failed with error code: 80049217",
    "innerError": {
      "request-id": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxx",
      "date": "2018-06-12T14:19:49"
    }
  }
}
10:19:48.1 (257254508)|METHOD_EXIT|[1]|000000000000000|AuthCallout.basicAuthCallout()
10:19:48.1 (258832440)|CODE_UNIT_FINISHED|execute_anonymous_apex
10:19:48.1 (259654615)|EXECUTION_FINISHED

The funny thing about my Named Credential is that under Authentication Status, it says "Authenticated" after it completes the Authentication Flow on Save. I also don't have the "Generate Authorization Header" box checked.

Best Answer

Manually generating a refresh token and putting it in to Salesforce is not supported. You need to check the documentation for your provider; typically, they require a special "scope" in order to provide a refresh token (typically "offline" or "refresh" or something). The refresh token is stored by Salesforce and automatically generates new access tokens on demand automatically during a 401 error.

There's no place to enter such a token because it's supposed to be obtained during the login flow, and is automatically stored securely by the platform. For example, if you were connecting to another Salesforce org, you'd probably use a scope like "api,refresh_token", which would indicate that you're requesting API access and a refresh token.

Related Topic