I am using a Tooling API credential to authenticate against the same Salesforce org so that I can get some tooling API data in Apex. I am using oauth 2 and initially my integration user has to go under Setup > Security > Named Credentials > Edit > Save in order to authentcate upon which they are able to access the data.
The issue is when the bearer token expires, I am getting a 401 and a message saying:
[{"message":"Session expired or invalid","errorCode":"INVALID_SESSION_ID"}]
I thought that the named credential handled the refresh token business automatically but that does not seem to be the case.
My Apex code:
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:Tooling_API_Credential'+'/services/data/v54.0/jobs/query/');
req.setHeader('Authorization', 'Bearer ' + '{!$Credential.OAuthToken}');
req.setHeader('Content-Type', 'application/json');
req.setMethod('GET');
HttpResponse res = h.send(req);
while (res.getStatusCode() == 302) {
req.setEndpoint(res.getHeader('Location'));
res = new Http().send(req);
}
String issuedAt = null;
JSONParser jobParser = null;
Map<String, Object> m = (Map<String, Object>)JSON.deserializeUntyped(res.getBody());
My Auth Provider:
As you can see I am using the scopes of full & refresh_token. I also looked at Named Credential: Authentication process and refresh token but that was not much help. I also saw this by Salesforce: https://help.salesforce.com/s/articleView?id=000381864&type=1 but I guess I am not clear whether a dummy call needs to be made (considering I am not using SOAP) or a named credential is smart enough to do it all.
Why is the named credential not handling the automatic refresh token functionality? Please help.